본문 바로가기
Problem Solving/LeetCode

[LeetCode] 67. Add Binary - Java

by graycode 2026. 5. 21.

 문제 링크

 

Add Binary - LeetCode

Can you solve this real interview question? Add Binary - Given two binary strings a and b, return their sum as a binary string.   Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101"   Constraints: *

leetcode.com

 

 풀이 코드

public class Solution {

    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int i = a.length() - 1, j = b.length() - 1, carry = 0;
        while (i >= 0 || j >= 0) {
            int sum = carry;
            if (i >= 0) sum += a.charAt(i--) - '0';
            if (j >= 0) sum += b.charAt(j--) - '0';
            sb.append(sum % 2);
            carry = sum / 2;
        }

        return carry != 0 ? sb.append(carry).reverse().toString() : sb.reverse().toString();
    }

}

댓글