[LeetCode] 67. Add Binary

Given two binary strings a and b, return their sum as a binary string.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

二进制求和。

给你两个二进制字符串,返回它们的和(用二进制表示)。输入为 非空 字符串且只包含数字 1 和 0

影子题415,是十进制的加法。做法甚至代码几乎都是一样的。

题意是给两个用字符串表示的二进制数字,请返回他们的和,也用字符串表示。思路是按位读取数字,从最低位开始两两相加,之后将(加和%2)append到结果集。为什么要将加和%2是因为这是二进制的计算,之后计算carry的时候也是需要除以2而不是除以10。

时间O(n)

空间O(1)

Java实现

class Solution {
    public String addBinary(String a, String b) {
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
        int sum = 0;
        StringBuilder sb = new StringBuilder();
        while (i >= 0 || j >= 0 || carry > 0) {
            int x = i >= 0 ? a.charAt(i--) - '0' : 0;
            int y = j >= 0 ? b.charAt(j--) - '0' : 0;
            sum = x + y + carry;
            sb.append(sum % 2);
            carry = sum / 2;
        }
        return sb.reverse().toString();
    }
}

 

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 题目总结

posted @ 2020-03-27 01:29  CNoodle  阅读(400)  评论(0编辑  收藏  举报