题目描述
高精度加法,相当于 a+b problem,不用考虑负数。
输入格式
分两行输入。 a , b ≤ 1 0 500 a,b \leq 10^{500} a,b≤10500。
输出格式
输出只有一行,代表 a + b a+b a+b 的值。
样例 #1
样例输入 #1
1
1
样例输出 #1
2
样例 #2
样例输入 #2
1001
9099
样例输出 #2
10100
解析
一、主要思路
- 由于输入的数字太大,用字符串保存输入。
- 对比较短的那个字符串,在前面进行补0操作。
- 设置变量保存进位。
- 核心代码是这部分:
for(int i = length-1; i>=0; i--){、
//保存当前i位置计算结果
temp = a[i]-'0'+b[i]-'0'+carry;
//当前i位置计算结果,除掉进位,保存到结果
result= char(temp%10+'0') + result;
//保存进位
carry = temp/10;
}
if(carry !=0){
//若运算的最后存在进位则将其保存进结果
result = char(carry+'0') + result;
}
二、代码
#include <iostream>
using namespace std;
string add(string a, string b){
int a_len=a.length();
int b_len=b.length();
//进行补0操作
if(a_len>b_len){
for(int i=0; i < a_len-b_len; i ++){
b='0'+b;
}
}else{
for(int i=0; i < b_len-a_len; i ++){
a='0'+a;
}
}
int carry = 0;
string result;
int temp;
int length = a.length();
for(int i = length-1; i>=0; i--){
temp = a[i]-'0'+b[i]-'0'+carry;
result= char(temp%10+'0') + result;
carry = temp/10;
}
if(carry !=0){
result = char(carry+'0') + result;
}
return result;
}
int main(){
string a, b;
cin >> a >> b;
cout << add(a, b);
}
三、注意点
- 字符串比较函数。
(1)比较对象:两个char*字符串
- 函数:int strcmp(const char* s1,const char* s2);
- 比较形式:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。
- 头文件:string.h
- 返回值:
(1) 当s1 < s2时,返回负数;
(2) 当s1 == s2时,返回值 = 0;
(3) 当s1 > s2时,返回正数。
(2)比较对象:两个string字符串
- 函数:compare()
- 比较形式:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。
- 返回值:
(1)当s1 < s2时,返回负数;
(2) 当s1 == s2时,返回值 = 0;
(3) 当s1 > s2时,返回正数。
- 记得初始化定义的值,博主没有把 carry 初始化为0,而在程序中又使用了这个未初始化的变量,一开始拿的0分(悲允)。
- 对于数字加字符的操作,可以参考链接:C++ int与char相加转换
这里进行补充说明:一般直接默认结果为int