1. 程式人生 > >19.2.12 [LeetCode 67] Add Binary

19.2.12 [LeetCode 67] Add Binary

leet font -- onclick ide 16px sed 分享 binary

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"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
技術分享圖片
 1 class Solution {
 2 public:
 3     string addBinary(string
a, string b) { 4 int i = a.size() - 1, j = b.size() - 1, last = 0; 5 string ans = ""; 6 while (i >= 0 && j >= 0) { 7 int now = a[i] + b[j] - 2 * 0 + last; 8 ans = (char)(now % 2 + 0) + ans; 9 last = now / 2; 10 i--, j--;
11 } 12 while (i >= 0) { 13 int now = a[i] - 0 + last; 14 ans = (char)(now % 2 + 0) + ans; 15 last = now / 2; 16 i--; 17 } 18 while (j >= 0) { 19 int now = b[j] - 0 + last; 20 ans = (char
)(now % 2 + 0) + ans; 21 last = now / 2; 22 j--; 23 } 24 if (last > 0) 25 ans = (char)(last + 0) + ans; 26 return ans; 27 } 28 };
View Code

19.2.12 [LeetCode 67] Add Binary