Fast straightforward Java solution (beat 97%)


  • 0
    public class Solution {
        public String addBinary(String a, String b) {
            char[] num1 = a.toCharArray(); 
            char[] num2 = b.toCharArray(); 
            char[] result = new char[Math.max(num1.length, num2.length)]; 
            int pos1= num1.length-1, pos2 = num2.length-1, pos = result.length-1;
            int carry = 0, sum = 0; 
            
            while (pos1 >= 0 && pos2 >= 0) { 
                sum = (num1[pos1--]-'0')+(num2[pos2--]-'0')+carry;
                result[pos--] = (sum%2 == 0)?'0':'1';
                carry = sum/2; 
            }
            
            while (pos1 >= 0) { 
                result[pos--] = (((num1[pos1]-'0')^carry) == 0)?'0':'1'; 
                carry = num1[pos1--]&carry; 
            }
            while (pos2 >= 0) {
                result[pos--] = (((num2[pos2]-'0')^carry) == 0)?'0':'1'; 
                carry = num2[pos2--]&carry; 
            }
            String res = "";
            if (carry == 1) {
                res = "1" + String.valueOf(result);
            } else {
                res = String.valueOf(result);
            }
            return res; 
        }
    }
    

Log in to reply
 

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