[Leetcode] Pow (x, n)

Source: Internet
Author: User

My writing method for this question may be different from that of others, and the overall thinking is the same.

The first step is to determine N, as shown in the code.

I want to convert exponential n to binary, for example, 3 ^ 45.

The binary value of 45 is 101101.

Scan from left to right and skip the first place.

If the bit is 0, the result is squared, that is, the result is multiplied by itself.

If the bit is 1, we need to multiply X in addition to the result square.


This principle is based on the exponential nature. If n = 10 (Binary), it is equivalent to 2. If n shifts one bit left, it is * 2, that is, 100 (Binary) that is, 4, multiplied by an X, which is equivalent

3 ^ 4*3 ^ 1 = 3 ^ 5-> 101 (Binary)

This method uses 2 as the base index square every time. It is often used in encryption algorithms because it is an exponential operation.

Based on the above rules, the result of 3 ^ 45 can be easily calculated.

 public double pow(double x, int n) {        if(n==1) return x;        else if(n>1) {            return pows(x,n);        }        else if(n==0){            return 1;        }        else {            return (double)(1.0/pows(x,Math.abs(n)));        }    }    public double pows(double x, int n){        String s=Integer.toBinaryString(n);        double result=x;        for(int i=1;i<=s.length()-1;i++){            char c=s.charAt(i);            result=result*result;            if(c=='1') result=result*x;        }        return result;    }


[Leetcode] Pow (x, n)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.