[poj-1001] Exponentiation Java解决
题目描述:
| Time Limit: 500MS | Memory Limit: 10000K | |
| Total Submissions: 126980 | Accepted: 30980 |
Description
Problems involving the computation of exact values of very large magnitude and precision are common. For example, the computation of the national debt is a taxing experience for many computer systems.
This problem requires that you write a program to compute the exact value of Rnwhere R is a real number ( 0.0 < R < 99.999 ) and n is an integer such that 0 < n <= 25.
This problem requires that you write a program to compute the exact value of Rnwhere R is a real number ( 0.0 < R < 99.999 ) and n is an integer such that 0 < n <= 25.
Input
The input will consist of a set of pairs of values for R and n. The R value will occupy columns 1 through 6, and the n value will be in columns 8 and 9.
Output
The output will consist of one line for each line of input giving the exact value of R^n. Leading zeros should be suppressed in the output. Insignificant trailing zeros must not be printed. Don't print the decimal point if the result is an integer.
Sample Input
95.123 12
0.4321 20
5.1234 15
6.7592 9
98.999 10
1.0100 12
Sample Output
548815620517731830194541.899025343415715973535967221869852721 .00000005148554641076956121994511276767154838481760200726351203835429763013462401 43992025569.928573701266488041146654993318703707511666295476720493953024 29448126.764121021618164430206909037173276672 90429072743629540498.107596019456651774561044010001 1.126825030131969720661201
分析:
(1)高精度要求:Java语言中使用BigDecimal类型可解决
(2)多余开头零以及结尾冗余零的去除
(3)最后要输出的是全部的数据,不能用科学计数法表示:转换为字符串即可解决
参考代码:
1 import java.math.BigDecimal; 2 import java.util.Scanner; 3 4 public class Poj1001 { 5 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 9 Scanner in = new Scanner(System.in); 10 11 while(in.hasNextBigDecimal()){//非常重要,题目要求要可输入多组 12 13 //题目中的数据显然是高精度要求,因此用Java中的大数类型 14 BigDecimal r = in.nextBigDecimal(); 15 int n = in.nextInt(); 16 17 BigDecimal res = r.pow(n); 18 19 //stripTrailingZeros方法可去除末尾多余的零 20 res = res.stripTrailingZeros(); 21 22 //不用科学计数法输出,转化为字符串形式 23 String ans = res.toPlainString(); 24 //去除多余输出的开头零 25 if(ans.startsWith("0.")){ 26 //输出去掉开头零之外的字符 27 ans = ans.substring(1); 28 } 29 30 System.out.println(ans); 31 } 32 33 34 35 } 36 37 }
欢迎互相交流哦!

浙公网安备 33010602011771号