x的n次幂 - 中等

*************

C++

topic: 50. Pow(x, n) - 力扣(LeetCode)

*************

Give the topic an inspection.

Today is a good day because I have done all day job just in the past few seconds. And I have time to have some fun in here.

pow(x, n) means the number of x is n. so the code can be written as follow.

int result = 1;

if ( int i = 0; i < n; i++)

{

result = result * x;

}

let's give it a try.

class Solution {
public:
    double myPow(double x, int n) {

        // 用于存储结果
        double result = 1;

        // 开始循环
        for (int i = 0; i < n; i++)
        {
            result = result * x;
        }

        return result;
    }
};

really nice. We have two cases are passed.

check the sample, if x is negative, then should play some mathematic tricks.

class Solution {
public:
    double myPow(double x, int n) {

        // 用于存储结果
        double result = 1;
        double help = 1;

        // 开始循环
        if (n > 0) //  幂是正的
        {
            for (int i = 0; i < n; i++)
            {
                result = result * x;
            }
        }
        else if (n == 0) // 任何数的0次幂是1
        {
            return 1;
        }
        else // 幂是负的结果得是倒数
        {
            n = - n;
            for(int i = 0; i < n; i++)
            {
                help   = help * x;
                result = 1 / help;
            }
        }

        return result;
    }
};

need a smarter way to figure it out.

x is a static variable while n can be splitted.

x^n = (x^(n/2))^2    当 n 为偶数时
x^n = x*(x^(n/2))^2  当 n 为奇数时

x^{a+b}=x^{a}\times x^{b}

Then dichotomy comes to me.

n = n / 2;

lets try the code.

class Solution {
public:
    double myPow(double x, int n) {

        if (n < 0)
        {
            x = 1 / x;
            n = -n;
        }

        // result用来存储结果
        double result = 1;
        while (n > 0)
        {
            if (n % 2 == 1) // 如果幂是奇数
            {
                result = result * x;
            }

            x = x * x; // x²,二分法减少循环次数

            n = n / 2; //向下取整,1.38 -> 1
        }

        return result;
        
    }
};

the minimum of the type int is -2147483648; I should know this.

type long long can fix it.

class Solution {
public:
    double myPow(double x, int n) {

        long long nn = n;

        if (n < 0)
        {
            x  = 1 / x;
            nn = -nn;
        }

        // result用来存储结果
        double result = 1;
        while (nn > 0)
        {
            if (nn % 2 == 1) // 如果幂是奇数
            {
                result = result * x;
            }

            x  = x * x; // x²,二分法减少循环次数
            nn = nn / 2; //向下取整,1.38 -> 1
        }

        return result;
        
    }
};

Have a good day.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值