[Leetcode] Pow (x, n)

Source: Internet
Author: User
Pow (x, n)

Implement POW (X,N).

Algorithm ideas:

There is nothing to say about the two-way question. Just be careful. This question is time-consuming.

Return POW (x, N> 1) * POW (x, N> 1) cannot pass. Therefore, POW (x, n/2) is obtained first. In fact, the time complexity is the same.

[Note]: The value range of N; n = integer. min_value,-N is out of range, so I used long for packaging.

The Code is as follows:

 1 public class Solution { 2   public double pow(double x, int n) { 3         return pow(x,(long)n); 4     } 5     public double pow(double x,long n){ 6         if(x == 0 || x == 1) return x; 7         if(n == 0) return 1; 8         if(n == 1) return x; 9         if(n < 0) return 1 / pow(x,-n);10         double tem = pow(x,n >> 1);11         if((n & 1 )== 0){12             return tem * tem;        13         }else{14             return tem * tem * x;                    15         }16     }17 }

 

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.