首页 > 编程语言 > 详细

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

时间:2020-10-04 20:04:53      阅读:30      评论:0      收藏:0      [点我收藏+]

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,因为会有超时的风险

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

原文:https://www.cnblogs.com/tao10203/p/13767647.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!