Post

[LeetCode 67] Add Binary

LeetCode 67 (Java)
[Add Binary] 문제 풀이

[LeetCode 67] Add Binary

문제 바로가기


Description


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


  • 1 <= a.length, b.length <= 10^4
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.







Code


내 제출


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();

        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;

        while (i >= 0 || j >= 0 || carry == 1) {
            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;
        }

        //System.out.println(sb.reverse());
        return sb.reverse().toString();
    }
}


RuntimeMemory
1 ms42.5 MB


다른 풀이


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
    public String addBinary(String a, String b) {
        StringBuilder result = new StringBuilder();
        
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
        
        while (i >= 0 || j >= 0 || carry == 1) {
            int sum = carry;
            
            if (i >= 0) {
                sum += a.charAt(i) - '0';
                i--;
            }
            
            if (j >= 0) {
                sum += b.charAt(j) - '0';
                j--;
            }
            
            result.append(sum % 2);
            carry = sum / 2;
        }
        
        return result.reverse().toString();
    }
}


Reference


  • https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0066.Plus%20One/Solution.java
This post is licensed under CC BY 4.0 by the author.