• [leetcode] Pow(x, n)


    Implement pow(x, n).

    https://oj.leetcode.com/problems/powx-n/

    思路:不要连续乘n次,会超时。递归求解,注意不要写成重复计算,有正负数处理。

    public class Solution {
    	public double pow(double x, int n) {
    		if (n == 0)
    			return 1;
    
    		double res = 1;
    		long limit = n;
    		limit = limit < 0 ? -limit : limit;
    		res = recursivePow(x, limit);
    
    		if (n < 0)
    			res = 1.0 / res;
    
    		return res;
    
    	}
    
    	private double recursivePow(double x, long n) {
    		if (n == 1)
    			return x;
    		double half = recursivePow(x, n / 2);
    		if (n % 2 == 0) {
    			return half * half;
    		} else {
    			return half * half * x;
    
    		}
    
    	}
    
    	public static void main(String[] args) {
    		System.out.println(new Solution().pow(1.00000, -2147483648));
    	}
    }

    第二遍记录:

      注意int变负数可能溢出 和 递归的写法,正确的写法只需logn次的递归。

    public class Solution {
        public double pow(double x, int n) {
            if(n==0)
                return 1;
            long m = n;
            m=m<0?(-m):m;
            double res;
            res = powHelper(x,m);
            if(n<0){
                res = 1.0/res;
            }
            return res;
        }
        
        private double powHelper(double x, long n){
            if(n==1)
                return x;
            double half = powHelper(x,n/2);
            if(n%2==1){
                return half*half*x;
            }
            else{
                return half*half;
            }
            
        }
        
    }

    第四遍记录:

    判断奇偶的时候,n&1要套上括号。

    if( (n&1) !=0)

    ...

    注意n=Integer.MAX_VALUE的情况,-n会溢出,需转成long。

  • 相关阅读:
    计算机书籍.网址
    MVC是必知必用的
    技术
    三色旗帜分类
    巴斯卡三角形
    Centos安装wine等组件的问题
    some software that is used to speed up your system
    驾照考试系统之流程图
    用静态成员函数调用非静态成员变量
    MFC 进度条控件
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810763.html
Copyright © 2020-2023  润新知