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
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
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
1 | -1000000 9 |
Sample Output
1 | -999,991 |
题目大意
计算输入的A和B的和,按照每三位以’,’分割的格式输出
把a+b的和转为字符串s。除了第一位是负号的情况,只要当前位的下标i满足(i + 1) % 3 == len % 3并且i不是最后一位,就在逐位输出的时候在该位输出后的后面加上一个逗号。
java实现
此处实现使用scanner类获取输入,这种获取输入的方法比较实用但是耗费时间较长,碰上限制时间的题目时,需要采用另一种方法来获取输入:
1 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); if(a+b==0){ String output = "0"; System.out.print(output); }else if(a+b >0){ String result = String.valueOf(a+b); String temp = ""; String output = ""; for(int i = 0;i<result.length();i++){ temp = temp + result.charAt(result.length()-1-i); if((i+1)%3==0 && i != result.length()-1){ temp = temp +","; } } for(int i =0;i<temp.length();i++){ output = output + temp.charAt(temp.length()-1-i); } System.out.print(output); }else{ String result = String.valueOf(-a-b); String temp = ""; String output = ""; for(int i = 0;i<result.length();i++){ temp = temp + result.charAt(result.length()-1-i); if((i+1)%3==0&& i != result.length()-1){ temp = temp +","; } } for(int i =0;i<temp.length();i++){ output = output + temp.charAt(temp.length()-1-i); } output = "-"+output; System.out.print(output); } sc.close(); } } |
C++实现 https://www.liuchuo.net/archives/1888 推荐实现