leetcode || 67、Add Binary

时间:2015-04-03 11:17:17   收藏:0   阅读:221

problem:

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

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

Hide Tags
 Math String
题意:二进制数相加,二进制数用string表示

thinking:

(1)这题简单,但是有一个坑很容易掉进去:二进制的数的低位在最右边,string的下标低位再最左边。

(2)我的处理方式是先把两个string 翻转,逆序存储结果,再把结果翻转。有点麻烦,但容易实现

(3)也可以不翻转,从字符串后面开始遍历

code:

class Solution {
public:
    string addBinary(string a, string b) {
        string::size_type len1=a.size();
        string::size_type len2=b.size();
        if(len1==0)
            return b;
        if(len2==0)
            return a;
        unsigned int count=min(len1,len2);
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());
        int flag=0;
        string ret;
        for(int i=0;i<count;i++)
        {
            int tmp= a.at(i)-'0'+b.at(i)-'0'+flag;
            cout<<"tmp: "<<tmp<<endl;
            flag=tmp/2;
            ret.push_back(tmp%2+'0');
        }
        if(len1==len2 && flag>0)   //进位
                    ret.push_back('1');
        if(len1>count)//a剩余
        {
            for(int j=count;j<len1;j++)
            {
                int tmp1=a.at(j)-'0'+flag;
                flag=tmp1/2;
                ret.push_back(tmp1%2+'0');
            }
            if(flag>0)
                ret.push_back('1');
        }
        if(len2>count)//b剩余
        {
            for(int k=count;k<len2;k++)
            {
                int tmp2=b.at(k)-'0'+flag;
                flag=tmp2/2;
                ret.push_back(tmp2%2+'0');
            }
            if(flag>0)
                ret.push_back('1');
        }
        reverse(ret.begin(),ret.end());
        return ret;
    }
};


原文:http://blog.csdn.net/hustyangju/article/details/44851903

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!