1001. A+B Format (20)
首先来分析题目,这题
输入:输入两个整数,a和b,a和b取值范围[-10^7, 10^7]
输出:按格式输出a和b两数的和
因为之前做乙级被整数取值范围坑了,所以代码使用了long long int,但实际上这一题使用int就足够。
前面加那么多头文件只是因为懒。
# define _CRT_SECURE_NO_WARNINGS # include <iostream> # include <string> # include <sstream> # include <vector> # include <algorithm> # include <functional> # include <iomanip> # include <ctime> # include <map> # include <math.h> # include <string.h> using namespace std; int main(void) { long long int a, b; long long int t; string out; char c; cin >> a >> b; a = a + b; bool check = false; if (a < 0) //小于0的情况,后续补'-' check = true; else if (a == 0) //等于0的情况,输出字符串out不会获得字符 { cout << 0 << endl; return 0; } int flag = 0; while (a != 0) //大于0的情况,逐个取位 { t = a % 10; a = a / 10; if (t < 0) t = -t; //负数情况,转换绝对值 flag++; c = (int)t + '0'; out = c + out; if (flag == 3 && a != 0) { out = ',' + out; //每3个数补充',',且这个','前面还会有数字 flag = 0; } } if (check) out = '-' + out; cout << out << endl; return 0; }