1.題目
給你兩個(gè)二進(jìn)制字符串 a 和 b,以二進(jìn)制字符串的形式返回它們的和。
示例 1:
輸入:a = “11”, b = “1”
輸出:“100”
示例 2:
輸入:a = “1010”, b = “1011”
輸出:“10101”
提示:
1 <= a.length, b.length <= 104
a 和 b 僅由字符 ‘0’ 或 ‘1’ 組成
字符串如果不是 “0” ,就不含前導(dǎo)零
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/add-binary
2.思路
(1)調(diào)用 API
先將 a 和 b 轉(zhuǎn)化成十進(jìn)制數(shù),求和后再轉(zhuǎn)化為二進(jìn)制數(shù),這里可以使用 Java 自帶的 API 來(lái)實(shí)現(xiàn),但是在 Java 中:
- 如果字符串超過(guò) 33 位,不能轉(zhuǎn)化為 Integer;
- 如果字符串超過(guò) 65 位,不能轉(zhuǎn)化為 Long;
- 如果字符串超過(guò) 500000001 位,不能轉(zhuǎn)化為 BigInteger;
因此,該思路的適用性不強(qiáng),這一點(diǎn)需要注意。
(2)模擬
本題可以使用模擬的方式來(lái)進(jìn)行二進(jìn)制求和,具體步驟與415.字符串相加這題十分相似,只不過(guò)進(jìn)制由十進(jìn)制變?yōu)榱硕M(jìn)制。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-487071.html
相關(guān)題目:
LeetCode_字符串_簡(jiǎn)單_415.字符串相加文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-487071.html
3.代碼實(shí)現(xiàn)(Java)
//思路1————調(diào)用 API
class Solution {
public String addBinary(String a, String b) {
return Integer.toBinaryString(
Integer.parseInt(a, 2) + Integer.parseInt(b, 2)
);
}
}
//思路2————模擬
class Solution {
public String addBinary(String a, String b) {
StringBuilder res = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
//進(jìn)位
int carry = 0;
while (i >= 0 || j >= 0 || carry != 0) {
int x = (i >= 0) ? a.charAt(i) - '0' : 0;
int y = (j >= 0) ? b.charAt(j) - '0' : 0;
int val = x + y + carry;
res.append(val % 2);
carry = val / 2;
i--;
j--;
}
return res.reverse().toString();
}
}
到了這里,關(guān)于LeetCode_字符串_簡(jiǎn)單_67.二進(jìn)制求和的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!