leetcode题记——Add Binary

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

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

class Solution {
    public String addBinary(String a, String b) {
        if(a.length()<b.length())
            return addBinary(b, a);
        //a.length大于b.length
        char l1[]=a.toCharArray();
        char l2[]=b.toCharArray();
        int f=0;
        int j=0;
        for(int i=l2.length-1;i>=0;i--){
            if(l1[l1.length-1-j]=='0'&&l2[i]=='0'){
                if(f==1)
                    l1[l1.length-1-j]='1';
                else
                    l1[l1.length-1-j]='0';
                f=0;
            }        
            else if(l1[l1.length-1-j]=='1'&&l2[i]=='1'){
                if(f==1)
                    l1[l1.length-1-j]='1';
                else
                    l1[l1.length-1-j]='0';
                f=1;
            }
            else{
                if(f==1){
                     l1[l1.length-1-j]='0';
                     f=1;
                }   
                else{
                    l1[l1.length-1-j]='1';
                    f=0;
                }
            }
            j++;
        }
        for(int i=l1.length-1-j;i>=0;i--){
            if(l1[i]=='0'){
                if(f==1)
                    l1[i]='1';
                else
                    l1[i]='0';
                f=0;
            }else{
                 if(f==1){
                     l1[i]='0';
                     f=1;
                }   
                else{
                    l1[i]='1';
                    f=0;
                }
            }  
        }
        char l[];
        if(f==1){
            l=new char[l1.length+1];
            for(int i=l1.length;i>0;i--){
                l[i]=l1[i-1];
            }
            l[0]='1';
        }else{
            l=new char[l1.length];
            for(int i=l1.length-1;i>=0;i--){
                l[i]=l1[i];
            }
        }
            String Ans=new String(l);
            return Ans;
    }
}



已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页