LeetCode67. Add Binary

题目链接:

https://leetcode.com/problems/add-binary/

题目描述:

将二进制字符串相加。

题目分析:

嗯,需要注意的就是C++中数字转换字符串的方法。

string numToStr(int i)
{
        stringstream ss;
        ss<<i;
        return ss.str();
}

代码:

class Solution {
public:
    string addBinary(string a, string b) {
        int aLen=a.size();
        int bLen=b.size();
        string result="";
        int i=aLen-1;
        int j=bLen-1;
        int tmp=0;
        while(i>=0 && j>=0){
            tmp += (a[i--]-'0' + b[j--]-'0');
            stringstream ss;
            ss << (tmp % 2);
            result += ss.str();
            tmp/=2;
        }
        while(i>=0){
            tmp+=(a[i--]-'0');
            stringstream ss;
            ss << (tmp % 2);
            result += ss.str();
            tmp/=2;
        }
        while(j>=0){
            tmp+=(b[j--]-'0');
            stringstream ss;
            ss << (tmp % 2);
            result += ss.str();
            tmp/=2;
        }
        if(tmp==1){
            result+='1';
        }
        return string(result.rbegin(),result.rend());
    }
};

你可能感兴趣的:(LeetCode,String,67)