(PAT)1001 A+B Format (20)

43 篇文章 0 订阅

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 推荐实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值