Solution by padding shorter string and update value digit-by-digit


  • 1
    C

    Here's my solution to this problem, inline comments added to help understand.

    public String addBinary(String a, String b){
        //get the length of both string
        int al = a.length();
        int bl = b.length();
        int maxl = Math.max(al,bl);
        
        //padding the shorter string to same length
        String paddedStr = (al>bl)?addPadding(b,maxl):addPadding(a,maxl);
        if(al>bl) b = paddedStr;
        else if(al<bl) a = paddedStr;
        
        StringBuilder result = new StringBuilder();
        //flag to record whether needs to advance 1 in higher digit
        boolean flag = false;
        
        for(int i = maxl-1; i>=0; i--){
            //based on lower digit's advance flag, update the sum digit and flag value
            if(a.charAt(i)==b.charAt(i) && a.charAt(i)=='1'){
                result.append((flag == false)?"0":"1");
                flag = true;
            }
            else if(a.charAt(i)!=b.charAt(i)){
                result.append((flag == true)?"0":"1");
            }
            else if(a.charAt(i)==b.charAt(i) && a.charAt(i)=='0' && flag == true){
                flag = false;
                result.append("1");
            }
            else{
                flag = false;
                result.append("0");
            }
        }
        
        //advance highest digit and expand the result string, if flag stay true
        if(flag==true){
            result.append("1");
        }
        
        //reverse the string to get final result
        return result.reverse().toString();
     }
     
     //padding the shorter string to the same length
     public String addPadding(String str, int length){
         StringBuilder sb = new StringBuilder();
         int i = 0;
         if(length==0){
        	 return "0";
         }
         
         //only padding '0' till length-str.length() position
         while(i < length-str.length()){
             sb.append("0");
             i++;
         }
         sb.append(str);
         return sb.toString();
     }

Log in to reply
 

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