This problem is the calculation of the real number of n-square problems, for such a high precision place, double is certainly not enough (the precision of double is only 16 bits). See the first feeling of the problem may need to use an array to calculate, but the more complex, looking for a more simple solution, found that BigDecimal can be used to deal with a valid bit more than 16 bits of the number. BigDecimal cannot use simple +-*/, which means that the BigDecimal class is actually encapsulated on a number basis.
The first version of the code was poorly written, and the submission always had 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 ();}}}
The next night to continue to modify, or did not pass, referring to how others wrote, found a very concise and efficient.
Import Java.math.bigdecimal;import Java.util.scanner;public class Main {public static void main (string[] args) {Scanner I n = 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);}}}
Comparing two pieces of code, my code can be optimized in three places (basically all optimized).
1. Data entry
The original use of BufferedReader is to read one line at a time, but not necessary, scanner function more appropriate, because scanner has Nextbigdecimal () and Nextint () function, follow-up does not need to convert the data format.
2. Calculation of power
BigDecimal has a POW () function that can be used directly, and it is completely unnecessary to use a for loop to calculate. (This step optimizes more performance, not the place to cause runtime error)
3. Result printing
Result.intvalue () and Result.doublevalue () compared with 1, are actually inaccurate. It is better to compare strings directly, and the code is more concise.
The accuracy of the attached, float, and double can be referred to in this
Http://www.cnblogs.com/fromchaos/archive/2010/12/07/1898698.html
POJ 1001 exponentiation