leetcode 34 : Pow(x, n)
Implement pow(x, n).
class Solution { public: double pow(double x, int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if( n==0) return 1; if( n==1) return x; bool sign = n>0 ? true : false; if(!sign) n = -n; double rel=0; rel = pow(x, n/2); rel *= rel; if(n%2){ rel *= x; } return sign ? rel : 1.0/rel; } };
public class Solution { public double pow(double x, int n) { // Start typing your Java solution below // DO NOT write main() function if(x==1.0) return 1; boolean negative = false; if(n<0) { negative = true; n=-n; } double res = 1.0; while(n>0) { if( (n & 1) ==1) { res *= x; } x*=x; n>>=1; } return negative ? 1.0/res : res; } }