当前位置:网站首页>【415. 字符串相加】
【415. 字符串相加】
2022-08-11 07:13:00 【安河桥畔】
字符串相加
题目来源
力扣(LeetCode):字符串相加
题目描述
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。
你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。
示例1
输入
num1 = “11”, num2 = “123”
输出
“134”
示例2
输入
num1 = “456”, num2 = “77”
输出
“533”
示例3
输入
num1 = “0”, num2 = “0”
输出
“0”
提示
- 1 <= num1.length, num2.length <= 104
- num1 和num2 都只包含数字 0-9
- num1 和num2 都不包含任何前导零
思路分析
- 运用列竖式计算的思想进行字符串相加
- 找出两个字符串中较长的,作为左操作数
- 定义一个给比较长的字符串长一个单位的字符串保存相加的结果,将这个字符串初始化为全’0’
- 对于数字字符的加法,因为数字的ASCII值都是连续的,所以将其中一个字符转化为数字即可,最终得到的结果仍为char类型,如’4’+3=‘7’。如果将所有字符都转换成int类型计算,最终还是要转换回char类型保存在字符串中
- 按位相加,有进位则给高位加1
- 最终得到的结果判断最高位为’0’,则删除最高位
代码展示
class Solution {
public:
string addStrings(string num1, string num2) {
//较长的数作作操作数
if (num1.size() < num2.size())
{
num1.swap(num2);
}
int LeftSize = num1.size();
int RightSize = num2.size();
int RetSize = LeftSize + 1;
string ret(RetSize, '0');//保存结果
for (int i = LeftSize - 1; i >= 0; i--)
{
ret[i + 1] += (num1[i] - '0');
//注意这里是判断RightSize - 1 >= 0,而不是RightSize>= 0
if (RightSize - 1 >= 0)
{
ret[i + 1] += num2[RightSize - 1] - '0';
}
//如果有进位,当前位-10,高位加1
if (ret[i + 1] > '9')
{
ret[i + 1] -= 10;
ret[i] += 1;
}
RightSize--;
}
if (ret[0] == '0')
{
ret.erase(0, 1);
}
return ret;
}
};
int main()
{
system("pause");
return 0;
}
总结
erase()的用法
边栏推荐
- 1076 Wifi密码 (15 分)
- leetcode: 69. Square root of x
- 基于微信小程序的租房小程序
- 1076 Wifi Password (15 points)
- tf.cast(), reduce_min(), reduce_max()
- DDR4内存条电路设计
- 【LeetCode每日一题】——682.棒球比赛
- 【Pytorch】nn.Linear,nn.Conv
- Active users of mobile banking grew rapidly in June, hitting a half-year high
- Find the latest staff salary and the last staff salary changes
猜你喜欢
随机推荐
求职简历这样写,轻松搞定面试官
1051 Multiplication of Complex Numbers (15 points)
记录一些遇见的bug——Lombok和Mapstruct的冲突导致,A component required a bean of type ‘com.XXX.controller.converter.
1101 How many times B is A (15 points)
1002 Write the number (20 points)
One-hot in TF
查询跟踪快递单号物流,智能分析物流中转有延误的单号
linux 安装mysql服务报错
2022年中国软饮料市场洞察
Dynamic Agent Learning
matplotlib
【Pytorch】nn.Linear,nn.Conv
tf中矩阵乘法
1091 N-Defensive Number (15 points)
CIKM 2022 AnalytiCup Competition: 联邦异质任务学习
matplotlib
The softmax function is used in TF;
我的创作纪念日丨感恩这365天来有你相伴,不忘初心,各自精彩
1.2-误差来源
国密规范 SM2 SM3 SM4