内容简介:问题描述输入格式两行,每行一个整数,每个整数不超过1000位
问题描述
在C/C++语言中,整型所能表示的范围一般为-231到231(大约21亿),即使long long型,一般也只能表示到-263到263。要想计算更加规模的数,就要用软件来扩展了,比如用数组或字符串来模拟更多规模的数及共运算。
输入格式
两行,每行一个整数,每个整数不超过1000位
输出格式
一行,两个整数的和。
样例输入
15464315464465465
样例输出
15464797786119616
数据规模和约定
每个整数不超过1000位
分析:1.模拟竖式加法,依次从往左加
2.如果刚开始两位数字位数不一样,短的用0补上,最后一次加法,如果有进位也要加上~
#include <iostream>
#include <string>
using namespace std;
string add(string s1, string s2) {
int len1 = s1.length(), len2 = s2.length();
if (len1 < len2) {
string t(len2 - len1, '0');
s1 = t + s1;
} else if (len2 < len1) {
string t(len1 - len2, '0');
s2 = t + s2;
}
string ans = s1;
int car = 0;
for (int i = s1.length() - 1; i >= 0; i--) {
ans[i] = (s1[i] - '0' + s2[i] - '0' + car) % 10 + '0';
car = (s1[i] - '0' + s2[i] - '0' + car) / 10;
}
if (car) ans = (char) (car + '0') + ans;
return ans;
}
int main() {
string s1, s2;
cin >> s1 >> s2;
cout << add(s1, s2);
return 0;
}
❤❤点击这里 -> 订阅PAT、蓝桥杯、GPLT天梯赛、LeetCode题解离线版❤❤
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Agile Web Development with Rails, Third Edition
Sam Ruby、Dave Thomas、David Heinemeier Hansson / Pragmatic Bookshelf / 2009-03-17 / USD 43.95
Rails just keeps on changing. Rails 2, released in 2008, brings hundreds of improvements, including new support for RESTful applications, new generator options, and so on. And, as importantly, we’ve a......一起来看看 《Agile Web Development with Rails, Third Edition》 这本书的介绍吧!