您的位置:首页 > 其它

67. Add Binary

2016-01-06 15:32 183 查看
1.需求

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

For example,

a = “11”

b = “1”

Return “100”.

2.代码

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
string addBinary(string a, string b) {

int c = 0;
int i = a.length() - 1;
int j = b.length() - 1;
string result = "";

while(i >= 0 || j >= 0 || c == 1){
c += i >= 0 ? a[i--]-'0':0;
c += j >= 0 ? b[j--]-'0':0;
result= (char)(c % 2 + '0') + result;
c /= 2;

}
return result;

}
};

int main()
{
Solution s;

cout << s.addBinary("11","1110") << endl;

}


参考资料:

/article/1323939.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: