zoukankan      html  css  js  c++  java
  • PAT 1001 A+B Format (20分) to_string()

    题目

    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;
    }
    
    
  • 相关阅读:
    CV 第十一课 Segmentation Localization Detection 下
    面经
    overfitting问题
    CV 第十一课 Segmentation Localization Detection 上
    CV 第十一课 Classification + Localization 中
    SVM的特点
    UNSW CV第二课 上 Image Prepocessing
    UNSW CV Assignment1
    UNSW CV 第一课 下 投影 RGB HSV
    HDU 4350
  • 原文地址:https://www.cnblogs.com/codervivi/p/12910413.html
Copyright © 2011-2022 走看看