Valid Number Problem


Description

LeetCode Problem 67.

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

Example 1:

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

Example 2:

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

Constraints:

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


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
    string addBinary(string a, string b) {
        int len1 = a.size(), len2 = b.size();
        int maxLen = max(len1, len2);
        string result;
        int s = 0, c = 0;
        
        for (int i = 0; i < maxLen; i ++) {
            s = c;
            if (i < len1)
                s += a[len1 - i - 1] - '0';
            if (i < len2)
                s += b[len2 - i - 1] - '0';
            c = s / 2;
            s = s % 2;
            result += to_string(s);
        }
        
        if (c != 0)
            result += to_string(c);
        
        reverse(result.begin(), result.end());
        return result;
    }
};




Related Posts

Valid Number Problem

LeetCode 65. Given a string s, return true if s...

Text Justification Problem

LeetCode 68. Given an array of strings words and a...

Valid Number Problem

LeetCode 67. A robot is located at the top-left corner...

Length Of Last Word Problem

LeetCode 58. Given a string s consisting of some words...

Zigzag Conversion Problem

LeetCode 6. Write the code that will take a string...

Wildcard Matching Problem

LeetCode 44. Write the code that will take a string...