[LeetCode] 67. Add Binary

二进制求和。题意是给两个用字符串表示的二进制数字,请返回他们的和,也用字符串表示。例子,

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

思路是按位读取数字,从最低位开始两两相加,之后将(加和%2)append到结果集。为什么要将加和%2是因为这是二进制的计算,之后计算carry的时候也是需要除以2而不是除以10。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public String addBinary(String a, String b) {
 3         StringBuilder sb = new StringBuilder();
 4         int i = a.length() - 1;
 5         int j = b.length() - 1;
 6         int remainder = 0;
 7         while (i >= 0 || j >= 0 || remainder > 0) {
 8             int sum = remainder;
 9             if (i >= 0) {
10                 sum += a.charAt(i) - '0';
11             }
12             i--;
13             if (j >= 0) {
14                 sum += b.charAt(j) - '0';
15             }
16             j--;
17             sb.append(sum % 2);
18             remainder = sum / 2;
19         }
20         return sb.reverse().toString();
21     }
22 }

 

JavaScript实现

 1 /**
 2  * @param {string} a
 3  * @param {string} b
 4  * @return {string}
 5  */
 6 var addBinary = function(a, b) {
 7     let i = a.length - 1;
 8     let j = b.length - 1;
 9     let carry = 0;
10     let res = '';
11     while (i >= 0 || j >= 0 || carry > 0) {
12         if (i >= 0) {
13             carry += parseInt(a[i]);
14         }
15         i--;
16         if (j >= 0) {
17             carry += parseInt(b[j]);
18         }
19         j--;
20         res = (carry % 2) + res;
21         carry = parseInt(carry / 2);
22     }
23     return res;
24 };

 

你可能感兴趣的:([LeetCode] 67. Add Binary)