Easy C++ solution using binary shift


  • 0
    H
    class Solution {
    public:
        double myPow(double x, int n) {
            double result = 1;
            double last = n > 0 ? x : 1/x;
            long r = abs((long)n);
            while (r > 0) {
                if (r & 1) result *= last;
                r >>= 1;
                last *= last;
            }
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.