[ZOJ-PAT practise] A+B Format

Time Limit: 1 Second      Memory Limit: 32768 KB

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

answer:
1 import java.io.IOException;
2 import java.util.*;
3
4 public class Main{
5 public static void main(String args[]) throws IOException {
6 char b;
7 int i;
8 long temp,sum,flag;
9 long [] num = new long[2];
10 num[0] = 0;
11 num[1] = 0;
12 temp = 0;
13 sum = 0;
14
15 flag = 1;
16
17 Scanner scanner = new Scanner(System.in);
18
19 String stringin = scanner.nextLine();
20
21
22 for(i =0; i < stringin.length();i++){
23 b = stringin.charAt(i);
24 if(b == '\r')
25 break;
26 else if( b == ' ')
27 { num[0] = temp*flag;
28 temp = 0;
29 flag = 1;
30 }
31 else if(b == '-' )
32 flag = -1;
33 else{
34 temp = temp*10 + ( b - '0');
35 }
36 }
37 num[1] = temp*flag;
38 sum = num[0]+num[1];
39 if(sum < 0)
40 {
41 System.out.print("-");
42 sum = ~sum + 1;
43 }
44 Main.print(sum);
45
46 }
47 public static void print(long num){
48 if(num >= 1000)
49 {
50 print(num/1000);
51 System.out.print(","+ (num/100)%10 + (num/10)%10 + num%10);
52 }
53 else{
54 System.out.print(num);
55 }
56 }
57 }

posted on 2011-04-29 14:58  DerDeath  阅读(514)  评论(0)    收藏  举报

导航

"); }); },1000); });