Clean & Easy Java solution, no bit-wise no mod


  • 0
    R
    public class Solution {
        public String addBinary(String a, String b) {
            StringBuilder sb = new StringBuilder();
            int i=a.length()-1,j=b.length()-1,inc = 0;
            while(i>=0||j>=0){
                int numa = 0,numb=0;
                if (i>=0) numa = a.charAt(i--)-'0';
                if(j>=0) numb = b.charAt(j--)-'0'; 
                if(numa + numb +inc > 1){ 
                    sb.append(numa + numb +inc-2);
                    inc =1;
                }
                else { 
                    sb.append(numa + numb +inc);
                    inc = 0;
                }
            }
            if(inc == 1){
                sb.append(1);
            }
            return sb.reverse().toString();
        }
    }
    

Log in to reply
 

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