coding复健之路之PAT甲级,从柳神那里学了很多,代码清晰可读性强,思路也可以细品,前辈的代码真好www然后建议按题目分类做,而不是按题库顺序做。
【置顶】【PAT】PAT甲级题目及分类总结(持续更新ing)
一、题目描述
类型:简单模拟
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).
二、输入
Each input file contains one test case. Each case contains a pair of integers a and b where − 1 0 6 ≤ a , b ≤ 1 0 6 −10^6 ≤a,b≤10^6 −106≤a,b≤106 . The numbers are separated by a space.
三、输出
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.
四、样例
输入:
-1000000 9
输出:
-999,991
代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
五、思路和代码
就是简单的两数相加 + 考虑负数 + 格式化输出。
格式化输出:从右到左每 3 位输出【,】,当前位的下标i满足**(i+1)%3==len%3**并且i不是最后一位。
#include <iostream>
using namespace std;
int main(){
int a, b;
cin >> a >> b;
string res = to_string(a+b);
int len = res.length();
for(int i = 0; i < len; i++){
cout << res[i];
if(res[i] == '-') continue;
if((i+1) % 3 == len % 3 && i != len-1) cout << ",";
}
return 0;
}
除了c++,java自带了格式化输出,但是耗时emmm
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
System.out.printf("%,d", a+b);
}
}