leetcode_Add Binary

描述:

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

思路:

将字符串从后向前进行相加,最后有进位的话再创造新的位数,最后将字符串反转,输出即可。

代码:

public String addBinary(String a, String b) {
        int len1=a.length();
        int len2=b.length();
        String string=null;
        if(len1>len2)
        {
        	string=a;
        	a=b;
        	b=string;
        }
        len1=a.length();
        len2=b.length();
        StringBuilder sBuilder=new StringBuilder();
        int temp=0;
        boolean flag=false;
        int span=len2-len1;
        int indexA=0;
        for(int i=len2-1;i>=0;i--)
        {
        	temp=0;
        	indexA=i-span;
        	if(indexA>=0)
        		temp+=a.charAt(indexA)-'0';
        	temp+=b.charAt(i)-'0';
        	if(flag)
        	{
        	    temp+=1;
        	    flag=false;
        	}
        	sBuilder.append(temp%2);
        	if(temp>=2)
        		flag=true;
        }
        if(flag)
        	sBuilder.append('1');
        return sBuilder.reverse().toString();
    }


你可能感兴趣的:(add,binary,reverse)