王廷瑋|數位醫療|智慧醫療: 67. Add Binary WFU

2024年7月4日 星期四

67. Add Binary

67. Add Binary


給定兩個二進制字符串 a 和 b,返回它們的和作為一個二進制字符串。

範例 1:

輸入:a = "11", b = "1" 輸出:"100"


Python


class Solution:
def addBinary(self, a: str, b: str) -> str:
# Initialize the result string and carry
result = []
carry = 0
# Initialize pointers for both strings starting from the end
i, j = len(a) - 1, len(b) - 1
# Iterate through both strings
while i >= 0 or j >= 0 or carry:
# Get the current digit of a and b or 0 if the pointer is out of range
digit_a = int(a[i]) if i >= 0 else 0
digit_b = int(b[j]) if j >= 0 else 0
# Calculate the sum and carry
total = digit_a + digit_b + carry
carry = total // 2
result.append(str(total % 2))
# Move the pointers
i -= 1
j -= 1
# Join the result and reverse it to get the final binary string
return ''.join(result[::-1])

16.56MB, 36ms


C++


#include <string>
#include <algorithm>

class Solution {
public:
std::string addBinary(std::string a, std::string b) {
std::string result;
int carry = 0;
int i = a.size() - 1;
int j = b.size() - 1;
while (i >= 0 || j >= 0 || carry) {
int digit_a = (i >= 0) ? a[i] - '0' : 0;
int digit_b = (j >= 0) ? b[j] - '0' : 0;
int total = digit_a + digit_b + carry;
carry = total / 2;
result.push_back((total % 2) + '0');
i--;
j--;
}
std::reverse(result.begin(), result.end());
return result;
}
};

7.86MB, 2ms


Javascript


/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let result = "";
let carry = 0;
let i = a.length - 1;
let j = b.length - 1;
while (i >= 0 || j >= 0 || carry) {
let digitA = i >= 0 ? parseInt(a[i]) : 0;
let digitB = j >= 0 ? parseInt(b[j]) : 0;
let total = digitA + digitB + carry;
carry = Math.floor(total / 2);
result = (total % 2) + result;
i--;
j--;
}
return result;
};

51.77MB, 62ms