您的位置:首页 > 编程语言 > C语言/C++

C++使用string大数运算——加法

2017-10-25 22:07 615 查看
具体的细节都在注释里面,要特别体会对string性质的利用

#include <iostream>
#include <string>
using namespace std;
string  add(string a , string b ) {
string tempa = a, tempb = b;
//这个过程是判断一下谁更长,然后我们从短的开始运算
if (tempb.length() > tempa.length()) {
tempa = b;
tempb = a;
}
//以上已经完成了得到长的和短的  并且使得b更短
//需要注意的是在累加的过程中我们规定
//从右往左:也即从字符串最后的位置作为起始位置
int j = tempa.length() - 1;
for (int i  = tempb.length() - 1; i >= 0; i --  ) {
tempa[j] += tempb[i] - '0';
printf("---%c\n", tempa[j] );
j--;
}

for (int i = tempa.length() - 1 ; i >= 1 ; i --)//这里先到达倒数第二位因为最后一位不一定什么情况
{
if (tempa[i] >  '9') {
tempa[i - 1] += 1;
tempa[i] -= 10;//千万别忘了进位之后的只保留原来的个位数
}
}
if (tempa[0] > '9')//注意是大于‘9’ 直接用编码比较
{
tempa[0] -= 10; //千万别忘了进位之后的只保留原来的个位数
tempa = "1" + tempa; //因为第一位可能进位所以进一位 这里很好的利用了string拼接的性质
}

return tempa;
}
int main(int argc, char const *argv[])
{
std::ios::sync_with_stdio(false);//这一步是关闭同步,可以减少cin cout时间
string a , b;
cin >> a;
cin >> b;
cout  << add(a, b);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐