Java solution


  • 0
    M

    class Solution {
    public String addBinary(String a, String b) {

      if(a.length() > b.length()){
            while(a.length()>b.length())
          b=  "0"+b;
        }
        
        
        if(a.length() < b.length()){
            while(a.length()<b.length())
          a=  "0"+a;
        }
        System.out.println("a:"+a);
    

    System.out.println("b:"+b);

    String result="";
    int carry=0;
    int ans=0;
    char[] char1 = a.toCharArray();
    char[] char2 = b.toCharArray();
    for(int i=a.length()-1;i >=0;i--)
    {
    int aa = char1[i] - '0';
    int bb = char2[i] - '0';

            ans=aa+bb+carry;
             if(ans==1){
              carry=0;
       
          }
             if(ans==0){
              carry=0;
             
          }
            if(ans==2)
            {
                carry=1;
                 ans=0;
            }
            if(ans==3)
            {
                 carry=1;
                ans=1; 
            }
         
    System.out.println("ans: "+ans);
    
    
       result =String.valueOf(ans) + result;
        }
    
       if(carry==1)
    result="1" +result;
        System.out.println("result: "+result);
    

    return result;
    }
    }


Log in to reply
 

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