求某数的N次幂,用for循环做,非常巧妙

题目:https://leetcode.com/problems/powx-n/description/

答案:虽然题目很简单,但是不能直接依次乘积,需要提高效率,也不能用递归,会stackoverflow,所以用迭代的方式解,非常巧妙。

class Solution {
public:
    double myPow(double x, int n) {
        double res = 1.0;
        for (int i = n; i != 0; i /= 2) {
            if (i % 2 != 0) res *= x;
            x *= x;
        }
        return n < 0 ? 1 / res : res;
    }
};

 

你可能感兴趣的:(求某数的N次幂,用for循环做,非常巧妙)