PAT甲级(Advanced Level)练习题 ——A+B Format (20)的Java实现

题目描述:
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 -1000000 <= a, b <= 1000000. 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

算法思路:
该题从题目中看,是一道较为简单的题目(送分),首先将输入读取后获得两个计算的数字,计算的结果可以分为负数和非负数,对于这两类结果我们进行分类讨论;因为对于负数来讲,由于其存在负号,那么倘若和负号一起连续出现长度为4,那么这个不能分隔;但对于非负数由于没有负号的存在,那么每三个长度就要隔开。
这里我们可以将整数型的结果先转换成字符串,然后利用Java当中的StringBuffer从字符串的最末尾开始每隔三个长度的数字就加一个“,”,同时注意结果为正负的讨论。

算法实现:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String line  = scanner.nextLine();
        String[] str = line.split(" ");
        int a = Integer.parseInt(str[0]);
        int b = Integer.parseInt(str[1]);
        int res = a+b;
        String str_res = String.valueOf(res);
        StringBuffer str_res2 = new StringBuffer(str_res);
        if (res < 0) {
            for (int i=str_res2.length()-3;i>1;i-=3){
                str_res2.insert(i,',');
            }
        } else if (res>=0) {
            for (int i=str_res2.length()-3;i>0;i-=3){
                str_res2.insert(i,',');
            } 
        }
        System.out.println(str_res2);
    }
}

提交结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值