You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Solution {
public:
string addBinary(string a, string b) {
string res;
int na = a.size(), nb = b.size(), n = max(na, nb), carry = 0;
if (na > nb) {
b = string(na - nb, '0') + b;
} else {
a = string(nb - na, '0') + a;
}
for (int i = n - 1; i >= 0; --i) {
int sum = (a[i] - '0') + (b[i] - '0') + carry;
res = to_string(sum % 2) + res;
carry = sum / 2;
}
return carry == 1 ? "1" + res : res;
}
};
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int m = a.size() - 1, n = b.size() - 1, carry = 0;
while (m >= 0 || n >= 0) {
int p = m >= 0 ? a[m--] - '0' : 0;
int q = n >= 0 ? b[n--] - '0' : 0;
int sum = p + q + carry;
res = to_string(sum % 2) + res;
carry = sum / 2;
}
return carry == 1 ? "1" + res : res;
}
};
请点击下方图片观看讲解视频
Click below image to watch YouTube Video
Given two binary strings
a
andb
, return their sum as a binary string.Example 1:
Example 2:
Constraints:
1 <= a.length, b.length <= 104
a
andb
consist only of'0'
or'1'
characters.二进制数相加,并且保存在 string 中,要注意的是如何将 string 和 int 之间互相转换,并且每位相加时,会有进位的可能,会影响之后相加的结果。而且两个输入 string 的长度也可能会不同。这时我们需要新建一个 string,它的长度是两条输入 string 中的较大的那个,并且把较短的那个输入 string 通过在开头加字符 ‘0’ 来补的较大的那个长度。这时候逐个从两个 string 的末尾开始取出字符,然后转为数字,相加,如果大于等于2,则标记进位标志 carry,并且给新 string 加入一个字符 ‘0’。代码如下:
解法一:
下面这种写法又巧妙又简洁,用了两个指针分别指向a和b的末尾,然后每次取出一个字符,转为数字,若无法取出字符则按0处理,然后定义进位 carry,初始化为0,将三者加起来,对2取余即为当前位的数字,对2取商即为当前进位的值,记得最后还要判断下 carry,如果为1的话,要在结果最前面加上一个1,参见代码如下:
解法二:
Github 同步地址:
#67
类似题目:
Add Binary
Multiply Strings
Plus One Linked List
Plus One
Add Two Numbers
Add to Array-Form of Integer
参考资料:
https://leetcode.com/problems/add-binary/
https://leetcode.com/problems/add-binary/discuss/24475/short-code-by-c
https://leetcode.com/problems/add-binary/discuss/24488/Short-AC-solution-in-Java-with-explanation
LeetCode All in One 题目讲解汇总(持续更新中...)
(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~)
喜欢请点赞,疼爱请打赏❤️~.~
微信打赏
|
Venmo 打赏
---|---
The text was updated successfully, but these errors were encountered: