04数字字符串求和问题
# 04 数字字符串求和问题
# 415 字符串相加 (opens new window)
给定两个由数字组成的字符串,求它们相加的结果。
输入是两个字符串,输出是一个整数,表示输入的数字和。
输入:num1 = "11", num2 = "123" 输出:"134"
解析:
因为相加运算是从后往前进行的,所以可以先翻转字符串也可以从字符串尾部开始,再逐位计算。这种类型的题考察的是细节,如进位、位数差等等。
从字符串尾部开始计算和,如果扫描超出其中一个字符串长度则用0值代替,如果两个字符串计算完毕要检查是否还存在进位。字符串的数值计算通过与字符'0'
比较得到。
class Solution {
public:
string addStrings(string num1, string num2) {
int tail1 = num1.length()-1, tail2 = num2.length()-1;
string ans = "";
int addbit = 0;
while(tail1>=0 || tail2>=0 || addbit!=0){
int x = 0, y = 0;
if(tail1 >= 0){
x = num1[tail1--] - '0';
}
if(tail2 >=0 ){
y = num2[tail2--] - '0';
}
int add = x + y + addbit;
// 记录当前位计算结果
ans.push_back(add % 10 + '0');
// 记录进位情况
if(add < 10){
addbit = 0;
}else{
addbit = 1;
}
}
reverse(ans.begin(),ans.end());
return ans;
}
};
# 67 二进制求和 (opens new window)
给你两个二进制字符串,返回它们的和(用二进制表示)
输入是两个字符串,输出是一个字符串,表示输入的二进制数字和。
输入: a = "1010", b = "1011" 输出: "10101"
解析:
本题和字符串相加类似,从尾部开始逐位运算,要注意进位和两个字符串位数差的情况。
class Solution {
public:
string addBinary(string a, string b) {
int taila = a.length()-1, tailb = b.length()-1;
string ans;
int addbit = 0;
while(taila>=0 || tailb>=0 || addbit){
int x = 0, y = 0;
if(taila >= 0){
x = a[taila--] - '0';
}
if(tailb >= 0){
y = b[tailb--] - '0';
}
int add = x + y + addbit;
char c = add % 2 + '0';
ans = c + ans;
if(add < 2){
addbit = 0;
}else{
addbit = 1;
}
}
return ans;
}
};
上次更新: 2023/11/19, 12:55:48