[LeetCode]Add Binary
2015-04-18 11:12
204 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
思路:把两个二进制串相加,返回加的结果。
从每个字符串最后一位开始加,同时要考虑到进位位。
ret+=((a[i]-'0')^(b[i-m+n]-'0')^cin+'0');
cin = (a[i]-'0'+b[i-m+n]-'0'+cin)>1?1:0;
特别注意数组不要越界,最好在最开始做个判断,把长的string设置为a,短的设置为b。
最后由于ret是反相加的,要把ret翻转就是最后的结果。
For example,
a =
"11"
b =
"1"
Return
"100".
思路:把两个二进制串相加,返回加的结果。
从每个字符串最后一位开始加,同时要考虑到进位位。
ret+=((a[i]-'0')^(b[i-m+n]-'0')^cin+'0');
cin = (a[i]-'0'+b[i-m+n]-'0'+cin)>1?1:0;
特别注意数组不要越界,最好在最开始做个判断,把长的string设置为a,短的设置为b。
最后由于ret是反相加的,要把ret翻转就是最后的结果。
class Solution { public: string addBinary(string a, string b) { int cin = 0; if(a.size()<b.size()){ string temp; temp = a; a = b; b = temp; } string ret; int m = a.size(); int n = b.size(); for(int i = m-1;i>=0;--i){ if(i>=m-n){ ret+=((a[i]-'0')^(b[i-m+n]-'0')^cin+'0'); cin = (a[i]-'0'+b[i-m+n]-'0'+cin)>1?1:0; } if(i<m-n){ ret+=((a[i]-'0')^cin+'0'); cin = (a[i]-'0'+cin)>1?1:0; } } if(cin>0) ret += '1'; reverse(ret); return ret; } void reverse(string &a){ int i=0; int j=a.size()-1; while(i<j){ char temp = a[i]; a[i] = a[j]; a[j] = temp; ++i; --j; } } };
相关文章推荐
- [LeetCode][Java] Add Binary
- (复习)[LeetCode]Add Binary
- [LeetCode] Add Binary 加法
- 【LeetCode】67. Add Binary
- LeetCode - Add Binary
- Leetcode: Add Binary
- 【LeetCode】-Add Binary
- LeetCode(56)-Add Binary
- leetcode 067 —— Add Binary
- [leetcode]67. Add Binary[facebook]
- 【LeetCode-面试算法经典-Java实现】【067-Add Binary(二进制加法)】
- leetcode_question_67 Add Binary
- Add Binary -- LeetCode
- 【LeetCode 67】Add Binary (Python)
- leetcode--Add binary
- Leetcode: Add Binary
- leetcode 66:Add Binary
- [leetcode]Add Binary
- 【leetcode】Add Binary
- leetCode 67. Add Binary 字符串