PAT: 1001. A+B Format (20)
2016-06-14 18:09
330 查看
问题描述:
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).
Input
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input
-1000000 9
Sample Output
-999,991
思路:先进行普通的A+B,将得到的结果转换成字符串处理,从后往前遍历加入一个空串,每隔插入一个逗号,注意最高位的数字前不要加逗号。
具体代码如下:
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).
Input
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input
-1000000 9
Sample Output
-999,991
思路:先进行普通的A+B,将得到的结果转换成字符串处理,从后往前遍历加入一个空串,每隔插入一个逗号,注意最高位的数字前不要加逗号。
具体代码如下:
#include <iostream> #include <sstream> #include <string> using namespace std; int main() { int a, b, s; cin >> a >> b; int c = a + b; stringstream ss; ss << c; string t; ss >> t; if(t[0] == '-') s = 1; else s = 0; string str = ""; int k = 0; for(int i = t.length() - 1; i >= s; i --) { str = t[i] + str; k ++; if(k == 3 && i != s) { str = ',' + str; k = 0; } } if(s == 1) str = '-' + str; cout << str << endl; return 0; }
相关文章推荐
- MFC
- 多线程
- 第十六周项目2—阅读程序(1)
- 设计模式:Observer(观察者)—— Guava EventBus
- 处理MariaDB Galera cluster初始化和启动报错两例
- 使用python脚本备份crontab定时任务
- java代码添加view
- Map的数据结构
- win10中显示资源管理器扩展
- 字符串分割与存入List集合
- ajax跨域请求结合springmvc后台代码学习整理
- android viewFlipper 循环播放图片
- 如何防止enter提交from表单
- 组策略应用——保护浏览器
- oracle 创建新用户 ,给新用户授权
- MySql基本数据类型
- 闰年理解
- 第二节课作业
- pure.css 学习记录
- 在Android中如何获取视频的第一帧图片并显示在一个ImageView中