题干要求:

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

解法一:

利用printf方法

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
	    int a = scanner.nextInt();
	    int b = scanner.nextInt();
	    scanner.close();
	    int sum = a + b;
	    if(sum < 0) {
	    	System.out.print("-");
	    	sum = 0 - sum;
	    }
	    if(sum >= 1000000) {
	    	System.out.printf("%d,%03d,%03d",sum/1000000,sum%1000000/1000,sum%1000);
	    }else if(sum >= 1000) {
	    	System.out.printf("%d,%03d", sum/1000,sum%1000);
	    }else {
	    	System.out.println(sum);
	    }
	    
	}
}

解法二:利用Java提供的强大的字符串处理API,两种解法都比较便捷

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
	    int a = scanner.nextInt();
	    int b = scanner.nextInt();
	    scanner.close();
	    int sum = a + b;
	    if(sum < 0) {
	    	System.out.print("-");
	    	sum = 0 - sum;
	    }
	    String sumStr = String.valueOf(sum);
	    int length = sumStr.length();
	    StringBuffer stringBuffer;
	    if(length <= 3) {
	    	System.out.println(sumStr);
	    } else if(length <= 6) {
	    	stringBuffer = new StringBuffer(sumStr);
	    	stringBuffer.insert(length - 3, ",");
	    	System.out.println(stringBuffer.toString());
	    } else {
	    	stringBuffer = new StringBuffer(sumStr);
	    	stringBuffer.insert(length - 3, ",");
	    	stringBuffer.insert(length - 6, ",");
	    	System.out.println(stringBuffer.toString());
	    }
		
	}
}


Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐