LeetCode67 Add Binary
题目:
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转换。
代码:
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 string result = ""; 5 int i = a.size() - 1, j = b.size() - 1, carry = 0; 6 while (i >= 0 || j >= 0 || carry == 1) { 7 int temp = carry; 8 carry = 0; 9 if (i >= 0) { 10 temp += a[i] - '0'; 11 i--; 12 } 13 if (j >= 0) { 14 temp += b[j] - '0'; 15 j--; 16 } 17 if (temp == 2) { 18 carry = 1; 19 temp = 0; 20 } 21 if (temp == 3) { 22 carry = 1; 23 temp = 1; 24 } 25 result = char('0' + temp) + result; 26 } 27 return result; 28 } 29 };