19.2.12 [LeetCode 67] Add Binary

Posted TobicYAL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.2.12 [LeetCode 67] Add 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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode67. Add Binary

LeetCode 67. Add Binary

*Leetcode 67. Add Binary

LeetCode 67. Add Binary

Leetcode 67. Add Binary

leetcode 67 Add Binary