当前位置:网站首页>【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()的用法
边栏推荐
- 1081 检查密码 (15 分)
- go-grpc TSL认证 解决 transport: authentication handshake failed: x509 certificate relies on ... ...
- The softmax function is used in TF;
- 1002 写出这个数 (20 分)
- 接口测试的基础流程和用例设计方法你知道吗?
- Activity的四种启动模式
- 1106 2019 Sequence (15 points)
- 2.1 - Gradient Descent
- 2022 China Soft Drink Market Insights
- Dynamic Agent Learning
猜你喜欢
随机推荐
Conditional statements in TF; where()
JRS303-Data Verification
What are the things that should be planned from the beginning when developing a project with Unity?How to avoid a huge pit in the later stage?
About # SQL problem: how to set the following data by commas into multiple lines, in the form of column display
Service的两种状态形式
3.1-分类-概率生成模型
1091 N-自守数 (15 分)
Keep track of your monthly income and expenses through bookkeeping
1096 big beautiful numbers (15 points)
Four operations in TF
1096 大美数 (15 分)
少年成就黑客,需要这些技能
Distributed Lock-Redission - Cache Consistency Solution
囍楽云任务源码
2022年中国软饮料市场洞察
【sdx62】XBL设置共享内存变量,然后内核层获取变量实现
Decrement operation in tf; tf.assign_sub()
2022-08-09 Group 4 Self-cultivation class study notes (every day)
1036 Programming with Obama (15 points)
接口测试的基础流程和用例设计方法你知道吗?