POJ 1001 Exponentiation
这个题目是要我们写高精度乘方。Java 的同学有福了,因为 BigDecimal 类可以帮助我们。但是使用其它语言的同学,嘿嘿……
就是不知道 ACM 的时候能不能混用语言啊,比如可否允许我这题用 C++ 那题用 Java.
原题地址:http://poj.org/problem?id=1001
POJ 1001 高精乘幂
描述
涉及大数量 (large magnitude) 和高精度 (large/high precision) 的精确值 (exact value) 计算的问题是很常见的。例如,对于很多计算机系统来说,国债 (national debt) 相关问题的计算是一个繁重的任务 (taxing experience).
这个问题需要你写一个程序,计算 Rn 的精确值,其中 R 是一个实数 (0.0 < R < 99.999), 且 n 是一个整数, 0 < n ≤ 25 .
输入
输入数据由一系列的 R n 数对 (pair of values) 组成。R 会占用 (occupy) 每一行的前 6 个字符,n 会占用第 8 和第 9 个字符。
输出
输出由若干行组成,每一行对应输入那行的 Rn 的精确结果。开头的 0 不能输出 (leading zeros should be suppressed in the output). 末尾的 (trailing) 无意义的 (insignificant) 0 也不能输出。如果结果是一个整数,不要输出小数点。
样例输入
95.123 12 0.4321 20 5.1234 15 6.7592 9 98.999 10 1.0100 12
样例输出
548815620517731830194541.899025343415715973535967221869852721 .00000005148554641076956121994511276767154838481760200726351203835429763013462401 43992025569.928573701266488041146654993318703707511666295476720493953024 29448126.764121021618164430206909037173276672 90429072743629540498.107596019456651774561044010001 1.126825030131969720661201
解题思路
因为我刚好是用 Java 的同学,所以我无耻地使用了 BigDecimal. 不过要注意,开头的 0 不能输出、结尾的 0 不能输出、整数不能有小数点这三条,其实条条针对 Java 啊!
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import java.math.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); while (cin.hasNextBigDecimal()) { BigDecimal decimal = cin.nextBigDecimal(); int exponent = cin.nextInt(); if (exponent == 0) { System.out.println('1'); continue; } if (decimal.equals(0)) { System.out.println('0'); continue; } String output = decimal.pow(exponent).toPlainString(); int posStart = 0, posEnd = output.length() - 1; for (int i = 0; i < output.length(); ++i) if (output.charAt(i) != '0') { posStart = i; break; } for (int i = output.length() - 1; i >= 0; --i) if (output.charAt(i) != '0') { posEnd = i; break; } if (output.charAt(posEnd) == '.') --posEnd; ++posEnd; System.out.println(output.substring(posStart, posEnd)); } } } |
原创文章,转载请注明来源:http://euyuil.com/2236/poj-1001-exponentiation/
