Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b ="1"
Return"100" .
<Solution>a =
b =
Return
這題也不難,和 plus one 思路一樣,處理好進位問題就好
code 如下
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string addBinary(string a, string b) { | |
int sum = 0, carry = 0; | |
int nums_1, nums_2; | |
int index_1 = a.length()-1, index_2 = b.length()-1; | |
string ans; | |
while(index_1 >= 0 || index_2 >= 0 ) { | |
nums_1 = (index_1 >= 0) ? static_cast<int>(a[index_1--] - '0') : 0; | |
nums_2 = (index_2 >= 0) ? static_cast<int>(b[index_2--] - '0') : 0; | |
sum = nums_1 + nums_2 + carry; | |
carry = sum / 2; | |
ans = to_string(sum%2) + ans; | |
} | |
return (carry > 0) ? "1" + ans : ans; | |
} | |
}; |
沒有留言:
張貼留言