My Accepted Solution. [Comments appreciated]


  • 0
    D
    public class Solution {
        public String addBinary(String a, String b) {
            StringBuilder result = new StringBuilder();
            int i, j, x, y, sum, carry;
            
            i = a.length() - 1;
            j = b.length() - 1;
            carry = 0;
            while(i >=0 && j >=0) {
                x = a.charAt(i) - '0'; y = b.charAt(j) - '0';
                sum = (x+y+carry) % 2;
                carry = (x+y+carry) / 2;
                result.append(sum);
                i--;
                j--;
            }
            
            while(i >= 0) {
                x = a.charAt(i) - '0';
                sum = (x+carry) % 2;
                carry = (x+carry) / 2;
                result.append(sum);
                i--;
            }
            
            while(j >= 0) {
                y = b.charAt(j) - '0';
                sum = (y+carry) % 2;
                carry = (y+carry) / 2;
                result.append(sum);
                j--;
            }
            
            if(carry > 0)   result.append(carry);
            
            result = result.reverse();
            
            return result.toString();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.