LeetCode67 Add Binary
2016-09-22 21:53
351 查看
题目:
Given two binary strings, return their sum (also a binary string). (Easy)
For example,
a =
b =
Return
分析:
思路很简单,就是按位依次相加,处理进位即可,循环条件里面可以写上carry == 1,用一个完整循环解决问题,而不用循环结束后再多加判定。
注意:题目给的是string,注意处理char和int转换。
代码:
Given two binary strings, return their sum (also a binary string). (Easy)
For example,
a =
"11"
b =
"1"
Return
"100".
分析:
思路很简单,就是按位依次相加,处理进位即可,循环条件里面可以写上carry == 1,用一个完整循环解决问题,而不用循环结束后再多加判定。
注意:题目给的是string,注意处理char和int转换。
代码:
class Solution { public: string addBinary(string a, string b) { string result = ""; int i = a.size() - 1, j = b.size() - 1, carry = 0; while (i >= 0 || j >= 0 || carry == 1) { int temp = carry; carry = 0; if (i >= 0) { temp += a[i] - '0'; i--; } if (j >= 0) { temp += b[j] - '0'; j--; } if (temp == 2) { carry = 1; temp = 0; } if (temp == 3) { carry = 1; temp = 1; } result = char('0' + temp) + result; } return result; } };
相关文章推荐
- [leetcode 67] Add Binary
- leetcode 67. Add Binary (高精度加法)
- 【leetcode c++】67 Add Binary
- LeetCode67 Add Binary
- LeetCode 67 Add Binary
- [Leetcode]#67 Add Binary
- LeetCode 67 — Add Binary(C++ Java Python)
- 小白笔记---------------------------------leetcode(67. Add Binary )
- [LeetCode By Python]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 67, easy] Add Binary
- Leetcode 67 Add Binary
- leetcode 67: Add Binary