[leetcode]Add Binary
阿新 • • 發佈:2018-11-10
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
分析:
二進位制求和,可以新定義一個string,用一個int型carry表示進位。從字串末尾開始相加,若carry為2,則向新字串裡開頭位置添0,carry置1;若carry小於2,則向新字串裡開頭位置添carry的值。遍歷完a、b較長的字串並且carry等於0為止。此外要注意字串與int型之間的轉換。
class Solution { public: string addBinary(string a, string b) { int len1 = a.size(); int len2 = b.size(); int carry = 0;//初始進位為0 string c = ""; int i = len1-1; int j = len2-1; if(len1 == 0) return b; if(len2 == 0) return a; while(i >= 0 || j >= 0 || carry > 0) { if(i >= 0) { carry += a[i] - '0'; i--; } if(j >= 0) { carry += b[j] - '0'; j--; } c.insert(c.begin(),carry % 2 + '0');//在c的開始位置插入低位求和的結果 carry /= 2;//若和為2,則進位為1 } return c; } };