double power (double a, unsigned int n) { double y = 1; double f = a; unsigned int k = n; while (k != 0) { if (k % 2 == 1) y *= f; k >>= 1; f *= f; } return y; }
但,它是不會通過的,因為尚需考慮 n 為負數時的情況:
public class Solution { public double myPow(double x, int n) { if( n < 0) return 1/x * myPow(1/x, -(n+1)); if( n == 0 ) return 1; if( n == 2 ) return x*x; if( n % 2 == 0 ) return myPow( myPow(x, n/2), 2); else return x*myPow( myPow(x, n/2), 2); } }
沒有留言:
張貼留言