LeetCode050 Pow(x, n)

详细见: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))
        


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值