67. Add Binary
/**
* Problem: LeetCode 67 - Add Binary
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
if (i >= 0) {
sum += a.charAt(i--) - '0';
}
if (j >= 0) {
sum += b.charAt(j--) - '0';
}
sb.append(sum % 2);
carry = sum / 2;
}
return sb.reverse().toString();
}
}
"""
Problem: LeetCode 67 - Add Binary
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
class Solution:
def addBinary(self, a: str, b: str) -> str:
res = []
i, j = len(a) - 1, len(b) - 1
carry = 0
while i >= 0 or j >= 0 or carry:
total = carry
if i >= 0:
total += int(a[i])
i -= 1
if j >= 0:
total += int(b[j])
j -= 1
res.append(str(total % 2))
carry = total // 2
return "".join(reversed(res))
/**
* Problem: LeetCode 67 - Add Binary
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
if (i >= 0) {
sum += a[i--] - '0';
}
if (j >= 0) {
sum += b[j--] - '0';
}
res += to_string(sum % 2);
carry = sum / 2;
}
reverse(res.begin(), res.end());
return res;
}
};
/**
* Problem: LeetCode 67 - Add Binary
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let i = a.length - 1;
let j = b.length - 1;
let carry = 0;
const res = [];
while (i >= 0 || j >= 0 || carry > 0) {
let sum = carry;
if (i >= 0) {
sum += a.charCodeAt(i--) - 48;
}
if (j >= 0) {
sum += b.charCodeAt(j--) - 48;
}
res.push(sum % 2);
carry = Math.floor(sum / 2);
}
return res.reverse().join('');
};
TIME COMPLEXITY
O(max(N, M))
SPACE COMPLEXITY
O(max(N, M))