04
05/2015
[LeetCode] Add Binary
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解题思路:
题意为两个字符串表示的二进制相加,求结果。记住常字符串与字符串变量能够相加,但是字符串不能与数字相加,字符不能与字符串相加。
class Solution { public: string addBinary(string a, string b) { int len1=a.length(); int len2=b.length(); int carry=0; string result=""; int i=len1-1, j=len2-1; while(i>=0&&j>=0){ int r = (a[i]-'0') + (b[j]-'0') + carry; result = (r%2==0 ? "0": "1") + result; carry = r/2; i--; j--; } while(i>=0){ int r = (a[i]-'0') + carry; result = (r%2==0 ? "0": "1") + result; carry = r/2; i--; } while(j>=0){ int r = (b[j]-'0') + carry; result = (r%2==0 ? "0": "1") + result; carry = r/2; j--; } if(carry>0){ result = "1" + result; } return result; } };
二次刷题(2015-08-03)
class Solution { public: string addBinary(string a, string b) { string result = ""; int len1=a.length(); int len2=b.length(); int carry = 0; int i = 1; while(i<=len1&&i<=len2){ int add = (a[len1 - i] - '0') + (b[len2 - i] - '0') + carry; carry = add / 2; result = std::to_string(add % 2) + result; i++; } while(i<=len1){ int add = (a[len1 - i] - '0') + carry; carry = add / 2; result = std::to_string(add % 2) + result; i++; } while(i<=len2){ int add = (b[len2 - i] - '0') + carry; carry = add / 2; result = std::to_string(add % 2) + result; i++; } if(carry!=0){ result = std::to_string(carry) + result; } return result; } };
转载请注明:康瑞部落 » [LeetCode] Add Binary
0 条评论