迟来的算法-快速幂算法-C语言实现

leetCode 50题,实现 pow(xn) ,即计算 x 的 n 次幂函数(即,xn)。

Version 1.0

double myPow(double x, int n){

    double y = 1;

    for(int i = 0;i<n;i++){

        y *=x;

    }

    return y;

}

问题:未考虑n为负数的场景,示例都没有看完。

 

Version 2.0

double myPow(double x, int n){

    double y = 1;

    if (n > 0 ) {

    for(int i = 0;i<n;i++){

            y *=x;

        }

    } else {

        for(int i = 0;i< abs(n);i++) {

            y /=x;

        }

    }

    return y;

}

 问题:超时,一个标为中等难度的确实不是暴力来搞就OK的。

 Verison 3.0  看了题解,了解到快速幂算法。

double quickMul(double x, int n) {

    if (n == 0) {

        return 1.0;

    }

    double y = quickMul(x, n / 2);

    return n % 2 == 0 ? y * y : y * y * x;

}

double myPow(double x, int n){

    return n >= 0 ? quickMul(x,n): 1.0 / quickMul(x,-n);

}

问题:Line 10: Char 42: runtime error: negation of -2147483648 cannot be represented in type 'int'; cast to an unsigned type to negate this value to itself [solution.c]

做了一些尝试后还是没有想到原因,最后对比题解,发现需要定义一个long long来处理n。

Version 4.0

double quickMul(double x, long long n) {

    if (n == 0) {

        return 1.0;

    }

    double y = quickMul(x, n / 2);

    return n % 2 == 0 ? y * y : y * y * x;

}

double myPow(double x, int n){

    long long N = n;

    return N >= 0 ? quickMul(x,N): 1.0 / quickMul(x,-N);

}

题目分析

1)快速幂算法的掌握和运用,pow(x,n)= pown(x,n/2)*pow(x,n/2)*(n%2==0?1:x)。

2)  有符号类型,负数取负存在溢出问题。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值