My Solution in Java, not Fancy but Easy to Understand


  • 1
    B

    public String addBinary(String a, String b) {
    //delete blanks;
    a = a.trim();
    b = b.trim();

    //special cases;
    if(a.equals("")) return b;
    if(b.equals("")) return a;
    
    //append "0" to make the length of both stings equal
    int diffLen = a.length()>b.length()?a.length()- b.length():b.length()-a.length();
    
    if(a.length()<b.length())
    {
    	for(int i = 0;i<diffLen;i++)
    	{
    		a = "0"+a;
    	}
    }else if(a.length()>b.length())
    {
    	for(int i = 0;i<diffLen;i++)
    	{
    		b = "0"+b;
    	}
    }
    
    //Transfer the string to an array of bytes;
    byte[] aa = a.getBytes();
    byte[] bb = b.getBytes();
    int aaLen = aa.length;
    
    //turn each element into 1 or 0;
    for(int i = 0;i<aaLen;i++)
    {
    	aa[i] -=48;
    	bb[i] -=48;
    }
    
    //simulate the addition
    int carry = 0;
    String res = "";
    for(int i = aaLen -1;i>=0;i--)
    {
    	int tmp = aa[i]+bb[i]+carry;
    	res = Integer.toString(tmp%2) + res;
    	carry = tmp>1?1:0;  			
    }
    
    //add the carry if it is 1;
    res = (carry==1)?("1"+res):res;
    
    //return result
    return res;	      
    

    }


Log in to reply
 

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