【Leetcode】50. Pow(x, n)
阿新 • • 發佈:2018-02-05
math plus 1.0 小數 log strong true ray arr
Implement pow(x, n).
Example 1:
Input: 2.00000, 10 Output: 1024.00000
Example 2:
Input: 2.10000, 3 Output: 9.26100
package medium; public class L50MyPow { // 調用Math.pow() 函數 public double mypow(double x, int n) { double nn = n; return Math.pow(x, nn); } //本題就x的n次方,如求2的4次方。可以4個2相乘,也可以先兩個2相乘,之後兩個4在相乘。public double myPow(double x, int n) { //防止n越界2147483647,用long類型的N來代替n long N = n; double result = 1.0; // double類型的x 判斷x是否為0 if ((x - 0.0 < -0.000000000001) && n < 0) { return 0.0; } //指數小於零,求得的數是用負指數相反數求得的值的倒數。 if (N < 0) { N= -N; x = 1 / x; } double current_product = x; for (long i = N; i > 0; i /= 2) { if ((i % 2) == 1) { result = result * current_product; } current_product = current_product * current_product; } returnresult; } public static void main(String[] args) { L50MyPow cc = new L50MyPow(); //測試負數的整數次方。 4.0 System.out.println(cc.myPow(-2, 2)); System.out.println("!!!!!!!!!!!!!!!!!!!"); //小數的負數次方 2.543114507074558E-5 double re = cc.myPow(34.00515, -3); System.out.println(re); //小數的大正整數次方次方 0.0 System.out.println(cc.myPow(0.00001, 2147483647)); } }
【Leetcode】50. Pow(x, n)