前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PAT 1001 A+B Format (20分) to_string()

PAT 1001 A+B Format (20分) to_string()

作者头像
vivi
发布2020-07-14 10:43:02
3570
发布2020-07-14 10:43:02
举报
文章被收录于专栏:vblogvblogvblog

题目

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 Specification: Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤10​6​​ . The numbers are separated by a space.

Output Specification: 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

题目解析

给出两个数字(-10000001000000之间),计算他们的和,以标准格式输出(形如 99,999,999

  • 首先,两个数都是-10000001000000之间,所以直接用int保存求和即可,不会溢出
  • 然后为了输出方便,将其转为字符串,(to_string()是c++11引入的新方法)
  • 从前往后逐个输出字符,如果是负数,第一个字符是 '-'
  • 什么时候要输出 ',' ,标准格式是从后往前三个一输出,假设转成字符串后的长度为len,那么 len % 3 就是最前面多出的长度,也就是第一个 ',' 出现的位置,后面的都可以三个一组,就隔三个,输出一个 ','。 比如 12,345,666len = 8len % 3 = 2,所以第2个数字后面加 ','第5个数字后面加 ',',第 8 个数字后加 ',',但是第8个是最后一个数字,所以要排除。所以 条件就是 i % 3 == len % 3,但是因为我们的下标是从0开始的,而我们是数数字个数判断,所以应该是 (i + 1) % 3 == len % 3 && (i != len % 3)

代码

#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;
    // 标准化格式 -xx,123,999
    if ((i + 1) % 3 == len % 3 && i != len - 1)
      cout << ",";
  }
  return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题目解析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档