Add Binary

题目:

 

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

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

分析:可以根据二进制的加法原理解决此问题,要注意string与int之间的转换。

代码如下:

        string addBinary(string a, string b) {
        int n1=a.length();
        if(n1==0)return b;
        int n2=b.length();
        if(n2==0)return a;
        string result;
        int t=0;
        if(n1<n2)
        {
            string tmp(a);
            a=b;
            b=tmp;
            int temp=n1;
            n1=n2;
            n2=temp;
        }
        for(int i=n2-1;i>=0;i--)
        {
            
            string tmp;
            tmp='0'+(int(a[n1-1]-'0')+int(b[i]-'0')+t)%2;//此句中int(a[n1-1]-'0')是string转int

                                                                                        //int + '0' 是int 转化为string
            result=tmp+result;
            t=(int(a[n1-1]-'0')+int(b[i]-'0')+t)/2;
            n1--;
        }
        for(int i=n1-1;i>=0;i--)
        {
            string tmp;
            tmp='0'+(int(a[i]-'0')+t)%2;
            result=tmp+result;
            t=(int(a[i]-'0')+t)/2;
        }
        if(t==1)
        {
            string tmp;
            tmp='0'+1;
            result=tmp+result;
            return result;
        }
        return result;
    }

 

你可能感兴趣的:(binary)