PAT甲级——1001 A+B Format (20分)
2024-09-07 04:02:51
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)
Sample Input:
-1000000 9
Sample Output:
-999,991
第一种方法,注意题目说明的数字范围,及时处理越界即可。
为啥捏,因为 int 是32位的,最大2的31次方。题目给的数据容易越界
第二种方法,使用to_string
将A+B的值转化为字符串,按需要的格式进行修改。
string s = to_string(a + b);
to_string的用法推荐查阅官方文档,表述清晰
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Convert numerical value to string
Returns a string with the representation of val.
第二种方法较为简单清晰。
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
string s = to_string(a + b);
int len = s.length();
for (int i = 0; i < len; i++) {
cout << s[i];
if (s[i] == '-')
continue;
if ((i + 1) % 3 == len % 3 && i != len - 1)
cout << ",";
}
return 0;
}
最新文章
- git review出现的问题
- 关于iOS地图定位中点击设置->;隐私->;定位服务 闪退问题
- 我的复杂的OpenCV编译之路(OpenCV3.1.0 + VS2010 + Win7)
- BZOJ-1196 公路修建问题 最小生成树Kruskal+(二分??)
- Linux 基础网络设置
- hdu 1059 多重背包
- C# 控制连接超时
- linux远程连接mysql数据库
- Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(五)
- prototype对象的真正作用
- DevOps探索
- 知识点3-6:HTML辅助方法
- mybatis逆向工程生成代码
- C#-WinForm 串口通信
- python_爬百度百科词条
- mybatis 动态 SQL 官方文档
- JavaScript是如何工作: 深入探索WebSocket和HTTP/2与SSE + 如何选择正确的路径!
- Jenkins与网站代码上线解决方案【转】
- poj 1182 (关系并查集) 食物链
- 连续的if语句