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

    Implement pow(x, n).

    Analysis:

    x^n = x^(n/2)*x^(n/2) (*x, if n is odd).

    NOTE: We need consider n<0, AND if n=Integer.MIN_VALUE, -n is actually larger than Integer.MAX_VALUE by 1, so we cannot simply take -n.

    Solution:

     1 public class Solution {
     2     public double pow(double x, int n) {
     3         if (x==0) return 0;
     4         if (n==0) return 1;
     5       
     6         double res;
     7         if (n>0)
     8             res = powRecur(x,n);
     9         else{
    10             if (n>Integer.MIN_VALUE)
    11                 res = powRecur(x,-n);
    12             else {
    13                 res = powRecur(x,-(n+1));
    14                 res = res*x;
    15             }
    16             res = 1 / res;
    17         }
    18         return res;
    19         
    20     }
    21 
    22     public double powRecur(double x, int n){
    23         if (n==1) return x;
    24 
    25         double temp = powRecur(x,n/2);
    26         double res = temp*temp;
    27         if (n%2==1) res = res*x;
    28         return res;
    29     }
    30 }

    Solution 2:

    Another method is to directly take care of the negative power in the recursion function.

     1 public class Solution {
     2     public double pow(double x, int n) {
     3         if (x==0) return 0;
     4         if (n==0) return 1;
     5       
     6         double res;
     7         res = powRecur(x,n);
     8         return res;
     9         
    10     }
    11 
    12     public double powRecur(double x, int n){
    13         if (n==1) return x;
    14         if (n==-1) return 1/x;
    15 
    16         double temp = powRecur(x,n/2);
    17         double res = temp*temp;
    18         if (n%2==1) res = res*x;
    19         if (n%2==-1) res = res*(1/x);
    20         return res;
    21     }
    22 }
  • 相关阅读:
    VS编译cmake工程提示 “无法识别的标记”错误解决方法
    Markdown
    latex公式
    ros:time::now()详解
    c++中PROTOBUF遍历所有属性及值
    ORB-SLAM3相关博文
    WSL2安装及GUI图形界面配置踩坑指南
    ROS与PCL数据转换
    手眼标定中AX=XB求解方法及MATLAB、C++代码
    正则表达式用于数据清洗
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4125525.html
Copyright © 2011-2022 走看看