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

    • Pow(x, n)
      Total Accepted: 88351 Total Submissions: 317095 Difficulty: Medium
      Implement pow(x, n).
      思路:a.循环迭代求解(O(n)n次乘法运算)
      仔细想想,做了很多重复工作
      b.如何利用已经结论呢
      28=222....2
      28=(24)ans(ans24)

      思路来了,二分,分奇偶讨论,复杂度为O(log(n))
    Input:2.00000 -2147483648
    Output:inf
    Expected:0.00000
    
    #define IMIN numeric_limits<int>::min()
    class Solution {
    public:
        double myPow(double x, int n) {
            int is_min=0;
            if(n<0){
                x=1/x;
                if(n==IMIN){n=abs(n+1);is_min=1;}//处理负数绝对值越界,并标记
                else n=abs(n);
            }
            if(n==0)return 1;
            int sign=-1;
            if(n%2==0)sign=0;//判断奇偶
            else sign=1;
            double left = myPow(x,n/2);//二分乘法
            double res=0;
            if(sign==0)res= left*left;
            else res= left*left*x;
            if(is_min)res = res*x;//为负数边界转为正数,少乘了一个
            return res;
        }
    };
  • 相关阅读:
    作为产品经理为什么选择开源GIS
    arcpy自动发布服务02
    rclone
    MinIO+Keepalived+Nginx
    Mysql-用户管理
    docker-compose
    docker-制造镜像
    docker-数据卷
    docker-容器操作
    docker-镜像操作
  • 原文地址:https://www.cnblogs.com/freeopen/p/5483006.html
Copyright © 2011-2022 走看看