zoukankan      html  css  js  c++  java
  • 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

    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

    -1000000 9
    

    Sample Output

    -999,991

     1 import java.util.*;
     2 public class Main {
     3     public static void main(String[] args) {
     4         Scanner in = new Scanner(System.in);
     5         int a = in.nextInt();
     6         int b = in.nextInt();
     7         String sum = String.valueOf(a + b);
     8         int firstDigit = sum.charAt(0) == '-' ? 1 : 0;
     9 
    10         //calculate length of new String contained commas
    11         int len = sum.length() - firstDigit;
    12         len = sum.length() + (len-1) / 3 ;
    13 
    14         char[] array = new char[len];
    15         int count = 0, j = len - 1;
    16         for (int i = sum.length() - 1; i >= firstDigit; i--) {
    17             if (count % 3 == 0 && count > 0) {
    18                 array[j--] = ',';
    19             }
    20             array[j--] = sum.charAt(i);
    21             count++;
    22         }
    23         if (firstDigit == 1) array[0] = '-';
    24         System.out.println(array);
    25 
    26     }
    27 }
  • 相关阅读:
    C++ 虚函数表解析
    函数调用运算符重载
    成员访问运算符重载
    递增和递减运算符重载
    java 如何查看jdk版本&位数
    oracle 11g完美卸载
    win10 你没有足够的权限执行此操作。
    maven 找不到或无法加载主类
    eclipse 如何对maven项目进行打包?
    Core Dataeasy出现的错误
  • 原文地址:https://www.cnblogs.com/BJUT-2010/p/5564829.html
Copyright © 2011-2022 走看看