题目描述 mplement pow(x, n). 代码 递归 123456789101112131415161718 public class { public double myPow(double x, int n) { if(n == 0) return 1; if(n < 0){ n = -n; x = 1 / x; //如果不知道溢出后刚好n没变,就用if else if(n == Integer.MIN_VALUE){ n = Integer.MAX_VALUE; x = x * x; } } return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); }} 迭代 1234567891011121314151617181920212223242526272829303132333435 public class Solution{ public double myPow(double x, int n){ if(n == 0) return 1; // if(n < 0){ // if(n == Integer.MIN_VALUE){ // x = 1 / x; // x = x * x; // n = Integer.MAX_VALUE; // }else{ // n = -n; // x = 1/x; // } // } if(n < 0){ n = -n; x = 1 / x; //如果不知道溢出后刚好n没变,就用if else if(n == Integer.MIN_VALUE){ n = Integer.MAX_VALUE; x = x * x; } } double ans = 1; while(n > 0){ if((n & 1) == 1) ans *= x; x *= x; n >>= 1; } return ans; }} 赞微海报分享
近期评论