67. Add Binary
Question:
Given two binary strings a and b, return their sum as a binary string.
Example:
Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Output: "10101"
Source code
Version 1
Idea:
I want to post my method originally, but the method is very inefficient (add two elements of string as Plus One, do the same thing for each bits.)
So, I refered to Huahua's Tech Road. Wow, it's a concise approach and coding, use only 1 while() to process.
This part, we can learn how to convert char to integer、how to convert integer to char、calculate a value of carry and output in reverse.
conditional ? Ture:False
to implement one line of if-else statement.At 12 line, it is a right shift operator.
int a[i] = 1; // binary: 00000001
int b[j] = 1; // binary: 00000001
int sum = a[i] + b[j] = 2 // binary: 00000010
int carry = sum >> 1; // binary: 00000001 (right shifts the bits of the number accordingly)
Then, ues - '0' to convert char to int as a[i--] - '0', because character '0' means 48.
Because there are three different value of sum, we need to convert integer to bit, it's shown as the following:
if sum = 0 // binary: 00000000
(sum & 1) = 0
if sum = 2 // binary: 00000010
(sum & 1) = 1
if sum = 3 // binary: 00000011
(sum & 1) = 1
Then, we can use + '0' to convert int to char.
Finally, the variable of res is our answer, but the content is in reverse, so we need to output the last as head, rbegin() and rend() are built-in functions in C++ STL. rbegin() can return a reverse iterator pointing to the last char. rend() can return a reverse iterator pointing to the theoretical element preceding the first char of the string.
Time complexity: O(n)
Space complexity: O(n)
1 | class Solution { |