[UVA][JAVA] 10464 - Big Big Real Numbers
Return of the Aztecs
Problem B: | Big Big Real Numbers |
Time Limit: 1 second Memory Limit: 32 MB |
Aztec warriors are very good at math (Sssh! It’s a secret information :). As an Aztec, little Ahuitzotl has his heart’s wish to be a great warrior. But he is not good at math. There is a tradition in Aztecs that foundation of being very good at math is to know how to add really big decimal point numbers. With this wish in his heart, little Ahuitzotl started to practice adding such big real numbers. He wants your help to become very good at math. He wants you to write a program for him so that when he adds two decimal numbers he can match his results with your programs output. You see, you have such a big responsibility (to help a kid being a great warrior :)
Input
First line of the input is a non negative integer N. Next N line follows a pair of real numbers separated by a space in each line. Negative real number can appear in the input. Length of each number can be 1000 digits both before and after decimal point. The Input ends at EOF. You can assume that no invalid number will be given as input.
Output
You have to print the result after adding every pair of numbers in different lines. There should be at least one digit after and before the decimal point and no trailing and leading zeros should be printed.
Sample Input
8 1111.332 1123.1112 .223 9.8963 0.002331 .0012 1111.20000 1.0000 004112.000 21.00 .123 .001 3.333 -1.111 -1.111 3.333
Sample Output
2234.4432 10.1193 0.003531 1112.2 4133.0 0.124 2.222 2.222
輸出比較麻煩點, 如果你有更好的 method 請告訴我
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int t = cin.nextInt();
while(cin.hasNext()) {
BigDecimal a, b;
a = new BigDecimal(cin.next());
b = new BigDecimal(cin.next());
String ans = a.add(b).toPlainString();
boolean flag = false;
int i, j;
for(i = 0; i < ans.length(); i++) {
if(ans.charAt(i) != '.')
System.out.print(ans.charAt(i));
else {
flag = true;
break;
}
}
if(flag == false)
System.out.println(".0");
else {
j = ans.length()-1;
while(ans.charAt(j) == '0') j--;
if(ans.charAt(j) == '.')
System.out.println(".0");
else {
for(; i <= j; i++)
System.out.print(ans.charAt(i));
System.out.println("");
}
}
}
}
}