前言
Problem:1001 A+B Format (20 分)
Tags:整型转字符串 字符串截断 (c++)
Difficulty:剧情模式
想流点汗想流点血死而无憾Address:1001 A+B Format (20 分)
问题描述
Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
两个整数相加,每三位加一’,'输出。
解题思路
-
题目本身简单,但需要技巧提速,对于这种问题转化为字符串会方便很多,利用
string to_string(int val)
转化; -
负数的话首先输出负号,再利用字符串截断函数
string.substr()
去掉负号的影响; -
接下来得到的字符串长度为 l e n len len,下标为 i i i,那么在下标为 i = l e n − 3 k i=len-3k i=len−3k 的字符输出前输出 ‘,’ 即可,也就是
(len-i)%3==0
时(除了 i = 0 i=0 i=0)。
参考代码
#include<iostream>
using namespace std;
void solution_1001() {
int a, b;
std::cin >> a >> b;
string str = to_string(a + b);
if (str[0] == '-') {
cout << '-';
str = str.substr(1);
}
int len = str.length();
for (int i = 0; i < len; i++) {
if ((len - i) % 3 == 0 && i != 0) {
cout << ',';
}
cout << str[i];
}
cout << endl;
}
int main() {
solution_1002();
return 0;
}
总结
-
整型转字符串函数原型:
string to_string(int val);
-
字符串截断:
string sub1 = s.substr(pos); // 表示以下标pos开始截断到结尾 string sub2 = s.substr(pos,n); // 表示以下标pos开始截断长度为n位