format python1001format python_[Python/Java](PAT)1001 A+B Format (20)

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

-1000000 9

1

-10000009

Sample Output

-999,991

1

-999,991

题目大意

? ? 计算输入的A和B的和,按照每三位以’,’分割的格式输出

? ? 把a+b的和转为字符串s。除了第一位是负号的情况,只要当前位的下标i满足(i + 1) % 3 == len % 3并且i不是最后一位,就在逐位输出的时候在该位输出后的后面加上一个逗号。

分析

使用python实现就直接相加然后格式化输出就可以了。

使用java实现,则先判断相加后是否是负数。是负数先输出负号。然后倒置字符串,每隔三个字符加一个逗号,且如果处于最后的位置则不用添加逗号。最后再翻转过来,输出即可。

python实现

Python

if __name__ == "__main__":

line = input().split(" ")

a, b = int(line[0]), int(line[1])

print('{:,}'.format(a+b))

1

2

3

4

if__name__=="__main__":

line=input().split(" ")

a,b=int(line[0]),int(line[1])

print('{:,}'.format(a+b))

java实现

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

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

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

importjava.io.BufferedReader;

importjava.io.InputStreamReader;

publicclassMain{

publicstaticvoidmain(String[]args)throwsException{

BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));

String[]line=br.readLine().split(" ");

br.close();

inttemp=Integer.valueOf(line[0])+Integer.valueOf(line[1]);

if(temp<0){

System.out.print("-");

}

Strings=String.valueOf(Math.abs(temp));

Stringa=newStringBuffer(s).reverse().toString();

Stringget="";

for(inti=0;i

get=get+a.charAt(i);

if((i+1)%3==0&&i!=a.length()-1){

get=get+',';

}

}

Stringout=newStringBuffer(get).reverse().toString();

System.out.print(out);

}

}

你可能感兴趣的:(format,python)