[LeetCode] Add Binary
2013-03-19 12:02
288 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
For example,
a =
"11"
b =
"1"
Return
"100".
class Solution { public: string addBinary(string a, string b) { // Start typing your C/C++ solution below // DO NOT write int main() function int lengtha=a.length(); int lengthb=b.length(); int maxlength=lengtha; if(lengthb > maxlength) maxlength=lengthb; int num1,num2,sum; int carry=0; string result=""; for(int i=maxlength-1;i>=0;i--) { if( lengtha-(maxlength-i) >= 0) { num1=a[lengtha-(maxlength-i)]-'0'; } else{ num1=0; } if( lengthb-(maxlength-i) >= 0) { num2=b[lengthb-(maxlength-i)]-'0'; } else{ num2=0; } sum=num1+num2+carry; if(sum>=2) { sum=sum-2; carry=1; } else{ carry=0; } char tmp='0'+sum; result=tmp+result; } if(carry==1) { char tmp='0'+carry; result=tmp+result; } return result; } };
相关文章推荐
- leetcode_67 add binary
- leetcode 67. Add Binary
- [leetcode] 67. Add Binary 解题报告
- leetcode 67. Add Binary (高精度加法)
- Leetcode - Add Binary
- Leetcode_67_Add Binary
- leetcode-67-Add Binary
- [LeetCode]67 Add Binary
- LeetCode67 Add Binary
- [Leetcode]Add Binary
- LeetCode:Add Binary
- LeetCode Add Binary
- LeetCode Add Binary
- LeetCode_Add Binary
- 和大神们学习每天一题(leetcode)-Add Binary
- LeetCode 67 Add Binary(二进制相加)(*)
- [LeetCode] Add Binary
- LeetCode_Add Binary
- LeetCode 之 Add Binary
- 【leetcode】Add Binary