PAT A1001 A+B Format C/C++/Go语言/Python题解及注意事项

Problem:

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).

计算a+b并将结果以标准形式输出——每三位数字用一个 逗号’,‘分隔(除非结果小于四位)。

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −. 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

思路

  首先将结果转换为字符串,由于我们需要顺序输出每位字符,但根据题目要求我们实际上需要从后往前数每三位添加一个 ‘,’ ,如果我们能找一个这样条件C:当下标 i 满C(i)==TRUE 时输出 ',' ,就可以从头到尾输出一遍字符串,得到正确答案。

  要找到条件C,我们可以从正序每三位增加一个 ',' 的情况出发,此时输出 ',' 的条件是 i % 3 == 0,那么与之对应:本题要满足的条件就是( n - ( i + 1 ) ) % 3 == 0,即(n - i - 1)% 3 == 0时输出 ','。

 

C/C++代码

 

#include <iostream>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    string s = to_string(a + b);
    for (int i = 0; i < s.size(); ++i)
    {
        cout << s[i];
        if (s[i] != '-' && i != s.size() - 1 && (s.size() - i - 1) % 3 == 0)
        {
            cout << ",";
        }
    }
    return 0;
}

Go代码

package main
 
import (
    "fmt"
    "strconv"
)
 
func main() {
    var a, b int
    fmt.Scan(&a, &b)
    s := strconv.Itoa(a + b)
    len := len(s)
    for i := 0; i < len; i++ {
        fmt.Printf("%c", s[i])
        if s[i] != '-' && i != len-1 && (len-i-1)%3 == 0 {
            fmt.Printf(",")
        }
    }
} 

Python代码

print(format((int(input())+int(input())),','))

 注:笔者并不建议在PAT中使用Python.

posted @ 2020-10-04 18:20  tao10203  阅读(197)  评论(0)    收藏  举报