LeetCode 67. Add Binary
2019-04-09 本文已影响0人
cb_guo
题目描述
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
题目思路
- 思路一、看高赞得到的答案,真是清晰易懂啊
class Solution {
public:
string addBinary(string a, string b) {
string result = "";
int i = a.size() - 1;
int j = b.size() - 1;
int sum = 0;
while(i >= 0 || j >= 0){
if(i >= 0) sum += a[i--] - '0';
if(j >= 0) sum += b[j--] - '0';
result.insert(0, to_string(sum%2));
sum /= 2;
}
if(sum) result.insert(0, "1");
return result;
}
};