当前位置:网站首页>【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()的用法
边栏推荐
猜你喜欢
1061 判断题 (15 分)
Active users of mobile banking grew rapidly in June, hitting a half-year high
The softmax function is used in TF;
Test cases are hard?Just have a hand
Keep track of your monthly income and expenses through bookkeeping
leetcode: 69. Square root of x
结合均线分析k线图的基本知识
Four operations in TF
1046 punches (15 points)
查询跟踪快递单号物流,智能分析物流中转有延误的单号
随机推荐
Unity开发者必备的C#脚本技巧
无服务器+域名也能搭建个人博客?真的,而且很快
TF中的One-hot
1051 Multiplication of Complex Numbers (15 points)
JUC并发编程
关于Excel实现分组求和最全文档
1106 2019 Sequence (15 points)
redis操作
测试用例很难?有手就行
为什么我使用C#操作MySQL进行中文查询失败
语音信号处理:预处理【预加重、分帧、加窗】
Two state forms of Service
1003 I want to pass (20 points)
Analysys and the Alliance of Small and Medium Banks jointly released the Hainan Digital Economy Index, so stay tuned!
2022 China Soft Drink Market Insights
Square, multi-power, square root calculation in Tf
Activity的四种状态
tf.reduce_mean()与tf.reduce_sum()
【latex异常和错误】Missing $ inserted.<inserted text>You can‘t use \spacefactor in math mode.输出文本要注意特殊字符的转义
[Recommender System]: Overview of Collaborative Filtering and Content-Based Filtering