1001 A+B Format

    xiaoxiao2024-11-04  76

    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

    题意就是将两数字相加,当和大于4位时 要以标准化格式输出:

    eg 1 000 000 输出 1,000,000;

    最初理解题意错误 : 认为每3位数字就用,隔开 eg 1 000 000 输出 100,000,0

    此种思路方法:

     将输出的数字和(单独处理字符串)转换位字符串,再通过字符串转换为字符数组 输出字符数组(每输出三个就输出一个,),

     

    (i+1)%3==0 && i!= arrs.length-1

     

    public static void main(String[] args){ Scanner sc = new Scanner(System.in); Integer a=sc.nextInt(); Integer b=sc.nextInt(); Integer c=a+b; if(c<0) System.out.print("-"); char [] arrs= String.valueOf(Math.abs(c)).toCharArray(); for(int i=0;i< arrs.length;i++){ System.out.print(arrs[i]); if((i+1)%3==0 && i!= arrs.length-1){ System.out.print(","); } } }

     

    正确思路的方法一: / %的运用     eg 输出十进制的千位 先用 /100除去百位上的数,再就可以取出十进制的范围

    import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Integer a=sc.nextInt(); Integer b=sc.nextInt(); // sc.close(); int c=a+b; if(c<0) System.out.print("-"); c=Math.abs(c); if(c>=1000000) System.out.printf("%d,%d%d%d,%d%d%d",c/1000000,c/100000,c/10000,c/1000,c/100,c/10,c); else if(c>=1000){ System.out.printf("%d,d",c/1000,c-c/1000*1000); }else{ System.out.println(c); } } }

    方法二:

    也可以直接格式化输出:

    public static void main(String[] args){ Scanner sc=new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); System.out.printf("%,d", a+b); }

     

     

    最新回复(0)