본문 바로가기

Algorithm/LeetCode

LeetCode 67. Add Binary

문제 링크: leetcode.com/problems/add-binary/

 

Add Binary - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 요약: 두개의 이진수가 문자열 형태(String)으로 주어질 때, 두 수를 더한 값을 출력하시오. (문자열 형태, 이진수형태)

 

문제 접근: 두 수를 더하는 문제는 보통 overflow만 조심하면 쉽다. 이진수이기 때문에, 맨 끝부터 하나씩 더하면 된다.

 

class Solution {
    public String addBinary(String a, String b) {
    // 자릿수 변화있는지 없는지 체크하는 용도
        int carry = 0;
        int currentAIndex = a.length() - 1;
        int currentBIndex = b.length() - 1;
        
        StringBuilder res = new StringBuilder();
        while (currentAIndex >= 0 || currentBIndex >= 0) {
            int aValue = 0;
            int bValue = 0;
            
            // 마지막 index끼리 더하기 위해서 거꾸로탐색
            if (currentAIndex >= 0) {
                aValue = Character.getNumericValue(a.charAt(currentAIndex));
                currentAIndex--;
            }
            
            if (currentBIndex >= 0) {
                bValue = Character.getNumericValue(b.charAt(currentBIndex));
                currentBIndex--;
            }
            
            int sum = aValue + bValue + carry;
            // sum이 1보다 크면 자릿수를 하나 올리고 2(2진수이기 때문)를 뺸다.
            if (sum > 1) {
                carry = 1;
                sum -=2;
            } else {
                carry = 0;
            }
            res.append(sum);
        }
        
        // 루프를 다 돌았는데 carry가 1이면 맨 앞자리 올림 처리해야한다.
        if (carry == 1) res.append(1);
        // 맨 마지막 자리부터 넣었으므로 거꾸로 출력
        return res.reverse().toString();
    }
}

계속 풀다보니까 easy난이도가 대부분 할만해지는것(?) 같다.