class Solution {
public:
string addBinary(string a, string b) {
}
};
67. 二进制求和
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1" 输出: "100"
示例 2:
输入: a = "1010", b = "1011" 输出: "10101"
提示:
'0'
或 '1'
组成。1 <= a.length, b.length <= 10^4
"0"
,就都不含前导零。原站题解
javascript 解法, 执行用时: 88 ms, 内存消耗: 43.1 MB, 提交时间: 2023-10-28 10:58:46
/** * @param {string} a * @param {string} b * @return {string} */ var addBinary = function(a, b) { let ans = ""; let ca = 0; for(let i = a.length - 1, j = b.length - 1;i >= 0 || j >= 0; i--, j--) { let sum = ca; sum += i >= 0 ? parseInt(a[i]) : 0; sum += j >= 0 ? parseInt(b[j]) : 0; ans += sum % 2; ca = Math.floor(sum / 2); } ans += ca == 1 ? ca : ""; return ans.split('').reverse().join(''); };
golang 解法, 执行用时: 0 ms, 内存消耗: 3.4 MB, 提交时间: 2023-10-28 10:58:21
func addBinary(a string, b string) string { ans := "" carry := 0 lenA, lenB := len(a), len(b) n := max(lenA, lenB) for i := 0; i < n; i++ { if i < lenA { carry += int(a[lenA-i-1] - '0') } if i < lenB { carry += int(b[lenB-i-1] - '0') } ans = strconv.Itoa(carry%2) + ans carry /= 2 } if carry > 0 { ans = "1" + ans } return ans } func max(x, y int) int { if x > y { return x } return y }
cpp 解法, 执行用时: 0 ms, 内存消耗: 6.6 MB, 提交时间: 2023-10-28 10:58:06
class Solution { public: string addBinary(string a, string b) { string ans; reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); int n = max(a.size(), b.size()), carry = 0; for (size_t i = 0; i < n; ++i) { carry += i < a.size() ? (a.at(i) == '1') : 0; carry += i < b.size() ? (b.at(i) == '1') : 0; ans.push_back((carry % 2) ? '1' : '0'); carry /= 2; } if (carry) { ans.push_back('1'); } reverse(ans.begin(), ans.end()); return ans; } };
python3 解法, 执行用时: 44 ms, 内存消耗: 15.9 MB, 提交时间: 2023-10-28 10:57:52
class Solution: def addBinary(self, a, b) -> str: x, y = int(a, 2), int(b, 2) while y: answer = x ^ y carry = (x & y) << 1 x, y = answer, carry return bin(x)[2:]
java 解法, 执行用时: 1 ms, 内存消耗: 40.1 MB, 提交时间: 2023-10-28 10:57:33
class Solution { public String addBinary1(String a, String b) { return Integer.toBinaryString( Integer.parseInt(a, 2) + Integer.parseInt(b, 2) ); } public String addBinary(String a, String b) { StringBuffer ans = new StringBuffer(); int n = Math.max(a.length(), b.length()), carry = 0; for (int i = 0; i < n; ++i) { carry += i < a.length() ? (a.charAt(a.length() - 1 - i) - '0') : 0; carry += i < b.length() ? (b.charAt(b.length() - 1 - i) - '0') : 0; ans.append((char) (carry % 2 + '0')); carry /= 2; } if (carry > 0) { ans.append('1'); } ans.reverse(); return ans.toString(); } }
python3 解法, 执行用时: 56 ms, 内存消耗: N/A, 提交时间: 2018-09-21 16:24:28
class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ return bin(int(a, 2) + int(b, 2))[2:]