My JAVA solution


  • 0
    S
    public class Solution {
        public String addBinary(String a, String b) {
            if(a.length() < b.length()){
                while(a.length() != b.length())
                    a = "0"+a;
            }else if(a.length() > b.length()){
                while(a.length() != b.length())
                    b = "0"+b;
            }
            int carry = 0, len = a.length();
            String res = "";
            for(int i=0;i<len;i++){
                int ch1 = a.charAt(len-1-i) - '0';
                int ch2 = b.charAt(len-1-i) - '0';
                res = (ch1 ^ ch2 ^ carry) + res;
                if(carry == 1)
    	            carry = (ch1 | ch2 );
    	        else	
    	            carry = (ch1 & ch2);
            }
            if(carry == 1)
                res = "1" + res;
            return res;
        }
    }

Log in to reply
 

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