详细见:leetcode.com/problems/powx-n
Java Solution: github
package leetcode;
public class P050_PowXN {
/*
* 1 ms
* 37.87%
*/
static class Solution1 {
public double myPow(double x, int n) {
return Math.pow(x, n);
}
}
/*
* 2 ms
* 6.16%
* 多想想,怎么写出没有bug的代码
*/
static class Solution2 {
public double myPow(double x, int n) {
double ans = 0.0;
boolean isNegative = n < 0;
long len = 0, num = isNegative ? -(long)n : n;
while (num != 0) {
len ++;
num = num >>> 1;
}
num = isNegative ? -(long)n : n;
double[] help = new double[(int)(len + 13)];
help[0] = 1;
help[1] = x;
long nn = 2;
int count = 1;
ans = x;
while (nn < num + 1) {
ans = ans * ans;
help[++ count] = ans;
nn = nn << 1;
}
ans = 1;
for (int i = 1; i != help.length; i ++) {
if (Math.abs(help[i]) < 0.00000001)
continue;
int times = (int)num & (1 << (i - 1));
if (times != 0)
ans *= help[i];
}
return isNegative ? 1/ans : ans;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/powx-n/
AC 6ms 40.00%
*/
#include <stdio.h>
#include <stdlib.h>
double myPow(double x, int n) {
int bits[32], i = 0, nc = 0, bn = 0, sign = n < 0;
double* d = NULL, ans = 1;
n = n < 0 ? -n : n;
for (bn = 0, nc = n; nc != 0 && bn < 32; bn ++) {
bits[bn] = nc % 2;
nc = nc / 2;
}
d = (double*) malloc(sizeof(double) * bn);
d[0] = x;
for (i = 1; i < bn; i ++)
d[i] = d[i - 1] * d[i - 1];
for (i = 0; i < bn; i ++) {
if (bits[i])
ans *= d[i];
}
return sign ? 1.0 / ans : ans;
}
int main() {
printf("%f\r\n", myPow(34.00515, -3));
return 0;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/powx-n
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月9日
@details: Solution: 52ms 37.49%
'''
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
bit_s, bit_n=[False]*32, 0
sign = n < 0
n = abs(n)
while n != 0:
bit_s[bit_n]=True if n%2==1 else False
bit_n+=1
n //= 2
x_arr, ans=[x], 1
for i in range(1, bit_n):
x_arr.append(x_arr[i-1]*x_arr[i-1])
for i in range(bit_n):
ans *= x_arr[i] if bit_s[i] else 1
return 1 / ans if sign else ans
if __name__ == "__main__":
print(Solution().myPow(2, -7))