POJ 1001 Exponentiation,pojexponentiation

來源:互聯網
上載者:User

POJ 1001 Exponentiation,pojexponentiation

這道題是計算實數的N次方問題,對於這樣要求高精度的地方,double是肯定不夠用的(double的精度只有16位)。看到題的第一感覺是可能需要用數組來計算,但越想越複雜,找找看有沒有比較簡單的解決方案,發現BigDecimal可以用來處理有效位超過16位的數。BigDecimal不能使用簡單的+-*/,說明BigDecimal類其實在數的基礎上進行了封裝。

第一版代碼寫得很爛,而且提交一直有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();}}}

第二天晚上繼續修改,還是沒通過,參考別人是怎麼寫的,發現了一個非常簡潔高效的代碼。
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);}}}

對比兩段代碼,My Code有三處可以最佳化(基本上全部進行了最佳化)。

1、資料輸入

當初使用BufferedReader是為了一次讀一行,但是沒必要,Scanner的功能更貼切,因為Scanner有nextBigDecimal()和nextInt()函數,後續還不需要轉換資料格式。

2、冪的計算

BigDecimal有個pow()函數可以直接使用,完全沒有必要使用for迴圈來計算。(這一步最佳化更多的是效能的提高,不是引起runtime error的地方)

3、結果列印

result.intValue()和result.doubleValue()與1比較,其實都不準確。還是直接比較字串更好,而且代碼更加簡潔。


附、float和double的精度問題可以參考這個

http://www.cnblogs.com/fromchaos/archive/2010/12/07/1898698.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.