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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10^6 ≤a,b≤10^6
. 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
1.审题:题目要求 通过输入两个数A和B计算相加的和,并用“,”每3位进行一次分割并输出最终的分割结果。a的范围是大于等于-10^6也就是a要求大于等于-1000000,b小于等于1000000;
思路:
1.通过Scanner输入并把输入的结果存放到一个一维数组中,由于在java中int的数据类型在范围之内可以使用int[];
2.为了简化变量的定义次数我们可以把数组定义成长度为3;第一个元素放A,第二个元素放B,第三个元素放A+B;
3.使用StringBuffer类或者StringBuilder类方便操作字符串;
4.关键的一步:关于如何分割字符串。
实现:
1.设置一个boolean变量作为flag判断原本数字的正负,如果是正数则不考虑符号问题,如果是负数则先取绝对值忽略负数的情况,并记录flag最后操作字符串以后把负号加回来。
2.考虑边界值:该题目计算得到的最小结果为负7位数,最大为正7位数,所以逗号最多出现2次。小于4位数则不出现逗号。
这道题目通过java实现的一些思路
import java.util.Scanner;
public class Main {
static StringBuffer buffer = new StringBuffer();
public static void main(String[] args) {
int input[] = new int[3];
Scanner scanner = new Scanner(System.in);
input[0] = scanner.nextInt();
input[1] = scanner.nextInt();
boolean flag = false;
input[2] = input[0]+input[1];
scanner.close();
if(input[2]<0){
flag = false;
input[2]=Math.abs(input[2]);
buffer.append(input[2]);
jiadouhao();
}
else{
flag = true;
buffer.append(input[2]);
jiadouhao();
}
if(!flag){
buffer.insert(0,"-");
}
System.out.print(buffer.toString());
}
//封装为一个加逗号的函数 操作静态的stringbuffer 由于是单线程操作所以不用考虑线程安全型的问题
public static void jiadouhao(){
String temp = buffer.toString();
if(temp.length()/3==0){
return;
}
if(temp.length()/3 ==1 &&temp.length()>=3 ){
if(temp.length()==3){
}else{
buffer.insert(buffer.length()-3,",");
}
}
if(temp.length()/3 ==2 && temp.length()>=6){
buffer.insert(buffer.length()-3,",");
if(temp.length()==7)
{
buffer.insert(buffer.length()-7,",");
}
}
}
}
原题目地址:
https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400