leetcode_question_67 Add Binary
2013-09-14 12:29
344 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
For example,
a =
"11"
b =
"1"
Return
"100".
bool isAllZero(string a) { for (int i = 0; i < a.length(); ++i) { if (a[i] != '0')return false; } return true; } string stringxor(string a, string b) { string res=""; int al = a.length()-1; int bl = b.length()-1; for (;al >=0 && bl >= 0; al--,bl--) { char tmp = '0' + (a[al]-'0')^(b[bl]-'0'); res = tmp + res; } if (al >= 0) res = a.substr(0,al+1) + res; if (bl >= 0) res = b.substr(0,bl+1) + res; return res; } string stringand(string a, string b) { string res=""; int al = a.length()-1; int bl = b.length()-1; for (;al >=0 && bl >= 0; al--,bl--) { char tmp = '0' + ((a[al]-'0')&(b[bl]-'0')); res = tmp + res; } return res; } string addBinary(string a, string b) { // Start typing your C/C++ solution below // DO NOT write int main() function if (a == "") return b; if (b == "") return a; string xorres = ""; string andres = ""; do { xorres = stringxor(a,b); andres = stringand(a,b); andres += '0'; a = xorres; b = andres; } while (!isAllZero(b)); int i = 0; for (; i < a.length(); ++i) if (a[i] != '0') break; if (i >= a.length()) a = "0"; else a = a.substr(i); return a; }
相关文章推荐
- leetcode_question_67 Add Binary
- LeetCode 67 - Add Binary
- Leetcode 67:Add Binary
- LeetCode 67 Add Binary(二进制相加)(*)
- 【LeetCode 67】 Add Binary
- Leetcode 67 Add Binary 大数加法+字符串处理
- leetcode 67. Add Binary (高精度加法)
- leetcode 67. Add Binary
- [LeetCode]67 Add Binary
- 【LeetCode】C# 67、Add Binary
- leetcode 67---Add Binary 二进制 进位 String
- LeetCode 67. Add Binary
- [leetcode 67] Add Binary
- LeetCode(67) Add Binary
- [leetcode]67. Add Binary[facebook]
- leetcode 67 Add Binary
- 【LeetCode】67. Add Binary
- Leetcode:67. Add Binary
- [leetcode][67] Add Binary
- Leetcode 67 Add Binary