Accepted Java Solution


  • -2
    W
    public class Solution {
        public String addBinary(String a, String b) {
            
            if(a == null || b ==null)return null;
            
            int pos = 0, aSize = a.length(), bSize = b.length();
            int maxSize = aSize >= bSize ? aSize : bSize;
            
            boolean inc = false; // flag of increment
            char c = '0', aa = '0', bb = '0';
            StringBuilder sb = new StringBuilder();
            
            while(pos < aSize && pos < bSize){
                
                aa = a.charAt(aSize-1-pos);
                bb = b.charAt(bSize-1-pos);
                
                if(aa != bb){
                    c = inc ? '0' : '1';
                }else if(aa == '1' && bb == '1'){
                    c = inc ? '1' : '0';
                    inc = true;
                }else {
                    c = inc ? '1' : '0';
                    inc = false;
                }
                sb.insert(0, c);
                
                pos++;
                
            }
            while(pos < bSize){ // b still left
                
                bb = b.charAt(bSize-1-pos);
                if(bb == '0'){
                    c = inc ? '1' : '0';
                    inc = false;
                }else{ // bb == '1'
                    c = inc ? '0' : '1';
                }
                sb.insert(0, c);
                
                pos++;
    
            }
            while(pos < aSize){ // a still left
                
                aa = a.charAt(aSize-1-pos);
                if(aa == '0'){
                    c = inc ? '1' : '0';
                    inc = false;
                }else{ // aa == '1'
                    c = inc ? '0' : '1';
                }
                sb.insert(0, c);
                
                pos++;
    
            }
            if(inc){
                sb.insert(0, '1'); // increment one bit more
            }
            
            return sb.toString();
        }
    }

Log in to reply
 

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