PAT 1001 A+B Format (20 分) Java

博客围绕计算a+b并以标准格式输出展开,输入为一对范围在 -1000000 到 1000000 的整数,输出需用逗号分隔。作者用Java实现,思路是将总和转为字符串,利用StringBuffer反转并添加逗号,最终测试案例全部通过。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

Question:

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 −1000000​​ ≤a,b≤1000000. 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

我的代码是用Java写的,因为最近另一个比赛是用Java报的。
思路:int类型的总和转化为String,然后利用StringBuffer的反转函数reverse(),进行颠倒转化,在这过程中,添加逗号“,”。最后将StringBuffer转化为String,输出结果。

import java.util.Scanner;

public class P1001 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		StringBuffer sb = new StringBuffer();
		int a = sc.nextInt();
		int b = sc.nextInt();
		int sum = a + b;
		String str = String.valueOf(sum);
		
		if((str.length()<=3&&sum>0)||(str.length()<=4&&sum<0)||sum == 0)
			System.out.println(str);
		else {
			if(sum<0) {
				int time = 0;
				for(int i = str.length()-1;i>=1;i--) {
					if(time%3==0&&time>0)
						sb.append(',');
					sb.append(str.charAt(i));
					time ++;
				}
				System.out.println("-"+sb.reverse().toString());
			}
			else {
				int time = 0;
				for(int i = str.length()-1;i>=0;i--) {
					if(time%3==0&&time>0)
						sb.append(',');
					sb.append(str.charAt(i));
					time ++;
				}
				System.out.println(sb.reverse().toString());
			}
		}
}
}

最后测试案例全过了,测试结果如下:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值