POJ 1001 Exponentiation
來源:程序員人生 發布時間:2015-02-07 09:11:56 閱讀次數:2804次
這道題是計算實數的N次方問題,對這樣要求高精度的地方,double是肯定不夠用的(double的精度只有16位)。看到題的第1感覺是可能需要用數組來計算,但越想越復雜,找找看有無比較簡單的解決方法,發現BigDecimal可以用來處理有效位超過16位的數。BigDecimal不能使用簡單的+-*/,說明BigDecimal類其實在數的基礎上進行了封裝。
初版代碼寫得很爛,而且提交1直有runtime error。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String text = br.readLine();
while(!text.isEmpty()){
String[] str = text.split(" ");
if(str.length == 2) {
BigDecimal R = new BigDecimal(str[0]);
BigDecimal result = R;
int N = Integer.parseInt(str[1]);
for(int i=1; i<N; i++){
result = result.multiply(R);
}
if(result.intValue() < 1) {
System.out.println(result.toPlainString().substring(1));
} else {
System.out.println(result.stripTrailingZeros());
}
}
text = br.readLine();
}
}
}
第2天晚上繼續修改,還是沒通過,參考他人是怎樣寫的,發現了1個非常簡潔高效的代碼。
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
BigDecimal R = in.nextBigDecimal();
int n = in.nextInt();
R = R.pow(n);
String str = R.stripTrailingZeros().toPlainString();
if (str.startsWith("0."))
str = str.substring(1);
System.out.println(str);
}
}
}
對照兩段代碼,我的代碼有3處可以優化(基本上全部進行了優化)。
1、數據輸入
當初使用BufferedReader是為了1次讀1行,但是沒必要,Scanner的功能更貼切,由于Scanner有nextBigDecimal()和nextInt()函數,后續還不需要轉換數據格式。
2、冪的計算
BigDecimal有個pow()函數可以直接使用,完全沒有必要使用for循環來計算。(這1步優化更多的是性能的提高,不是引發runtime error的地方)
3、結果打印
result.intValue()和result.doubleValue()與1比較,其實都不準確。還是直接比較字符串更好,而且代碼更加簡潔。
附、float和double的精度問題可以參考這個
http://www.cnblogs.com/fromchaos/archive/2010/12/07/1898698.html
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈