zoukankan      html  css  js  c++  java
  • Pow(x, n)

    Implement pow(xn).题目在这里,二分解法如下:

    class Solution {
    public:
        double pow(double x, int n) {
            double ans;
            if(n < 0){
                ans = power(x, -n);
                return (double)1 / ans;
            }else{
                return power(x, n);
            }
        }
        double power(double x, int n) {
            double ans;
            if(n == 0) ans=1;
            else
            {  ans=power(x*x, n/2);
               if(n%2==1) ans*=x;
             }
             return ans;
        }
    };
          还可以这么写:

    class Solution {
    public:
        double pow(double x, int n) {
            double ans;
            if(n < 0)
                return (double)1 / power(x, -n);
            else return power(x, n);
        }
        double power(double a, int n) {
            double ans = 1;
            while(n > 0){
                 if(n&1) ans *= a;   
                 a *= a;
                 n >>= 1;        
             }
             return ans;
        }
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    ThinkPHP
    ThinkPHP
    静态化
    静态化
    静态化
    设计模式
    sublime
    静态化
    OPTIMIZE TABLE 小解
    information_schema系列八(事物,锁)
  • 原文地址:https://www.cnblogs.com/Rex7/p/4752562.html
Copyright © 2011-2022 走看看