5/30/2020

[LeetCode] 67. Add Binary

Problem : https://leetcode.com/problems/add-binary/ 

Similar to problem 66. Plus One .
Simulate long addition process. Remember to handle the last carry when it is greater than zero.
Time Complexity = O ( M + N ).  M = length of a, N = length of b.

class Solution {
    public String addBinary(String a, String b) {
        int n = Math.max(a.length(), b.length()) + 1;
        char[] buffer = new char[n];

        int i = a.length() - 1;
        int j = b.length() - 1;
        int k = n - 1;

        int carry = 0;

        while (i >= 0 || j >= 0 || carry == 1) {
            int A =  i >= 0 ? a.charAt(i--) - '0' : 0;
            int B =  j >= 0 ? b.charAt(j--) - '0' : 0;
            buffer[k--] = (char)('0' + (A + B + carry) % 2);
            carry = (A + B + carry) / 2;
        }
       
        
        if (buffer[0] != 0) {
            return new String(buffer);
        }

        return new String(Arrays.copyOfRange(buffer, 1, n));
    }
}

Edited on 02/13/2023. Replace with an optimized Java version solution.

Edited on 01/09/2022. Replace with the Java version solution.

No comments:

Post a Comment