Loading

剑指 Offer 16. 数值的整数次方

https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/

class Solution {
    public double myPow(double x, int n) {
        if(x == 0) return 0;
        long b = n;
        double res = 1.0;
        // 当n < 0 的时候 
        if(b < 0){
            x = 1 / x;
            b = -b;
        }
        while(b > 0){
		//在这里需要判断次幂的奇偶性,如果是奇数,需要先消耗一个,让次幂变成偶数
            if((b & 1) == 1) res *= x;
		//当变成偶数的时候,
            x *= x;
            b >>= 1;
        }
        return res;
    }
}
posted @ 2022-02-28 16:08  Zhbeii  阅读(28)  评论(0)    收藏  举报