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≤106. 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
题目大意
计算输入的A和B的和,按照每三位以','分割的格式输出
把a+b的和转为字符串s。除了第一位是负号的情况,只要当前位的下标i满足(i + 1) % 3 == len % 3并且i不是最后一位,就在逐位输出的时候在该位输出后的后面加上一个逗号。
分析
使用python实现就直接相加然后格式化输出就可以了。
使用java实现,则先判断相加后是否是负数。是负数先输出负号。然后倒置字符串,每隔三个字符加一个逗号,且如果处于最后的位置则不用添加逗号。最后再翻转过来,输出即可。
python实现
if __name__ == "__main__":
line = input().split(" ")
a, b = int(line[0]), int(line[1])
print('{:,}'.format(a+b))
java实现
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
br.close();
int temp = Integer.valueOf(line[0]) + Integer.valueOf(line[1]);
if(temp < 0){
System.out.print("-");
}
String s = String.valueOf(Math.abs(temp));
String a = new StringBuffer(s).reverse().toString();
String get = "";
for(int i=0;i<a.length();i++){
get = get + a.charAt(i);
if((i+1) %3 == 0 && i != a.length() - 1){
get = get + ',';
}
}
String out = new StringBuffer(get).reverse().toString();
System.out.print(out);
}
}
通过这个例子可以看出,如果不想用C/C++来写PAT的话,python也勉强可以考虑用来解题,但是java真的太慢了