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

    题目

    Implement pow(x, n).
    
    Example 1:
    
    Input: 2.00000, 10
    Output: 1024.00000
    
    Example 2:
    
    Input: 2.10000, 3
    Output: 9.26100
    
    

    解析

    • 主要考察,时间复杂度,x^10=x^5x^5=(xx)^5避免重复计算
    • 对负值和最小的MIN处理
    
    // add 50. Pow(x, n)
    class Solution_50 {
    public:
    
    	double myPow(double x, int n) { //n正负之分
    
    		double ret = 1.0;
    		if (n == 0)
    		{
    			return (double)1;
    		}
    		else if (n > 0)
    		{
    			while (n--) //超时
    			{
    				ret *= x;
    			}
    		}
    		else
    		{
    			x = 1 / x;
    			while (n++)
    			{
    				ret *= x;
    			}
    		}
    
    		return ret;
    	}
    	double myPow2(double x, int n) { //n正负之分
    
    		double ret = 1.0;
    		if (n==0)
    		{
    			return (double)1;
    		}
    		if (n<0)
    		{
    			return 1 / x*myPow(x, n + 1); //递归太深
    		}
    		else
    		{
    			return x*myPow(x, n - 1);
    		}
    
    		return ret;
    	}
    
    	double myPow1(double x, int n) {
    		double ret = 1.0;
    		if (n == 0)
    		{
    			return (double)1;
    		}
    		if (n<0) //负数处理
    		{
    			ret = 1 / x; //防止最MIN溢出
    			x = 1 / x;
    			n = -(n+1);
    		}
    
    		if (n%2==0)
    		{
    			;
    		}
    		else
    		{
    			ret *= x; 
    			n--;
    		}
    		double temp = myPow(x, n / 2);
    		ret *= (temp*temp);
    
    		return ret;
    	}
    
    	// 链接:https://www.nowcoder.com/questionTerminal/0616061711c944d7bd318fb7eaeda8f6
    	double pow(double x, int n) {
    		if (n == 0) return 1;
    		if (n < 0) 
    			return 1 / x * pow(1 / x, -(n + 1));
    		if (n % 2 == 0) 
    			return pow(x * x, n / 2);
    		else 
    			return pow(x * x, n / 2) * x;
    	}
    };
    

    题目来源

  • 相关阅读:
    分页查询
    PDO
    投票
    租房子
    PHP增删改查
    PHP数据访问
    PHP三大特性-继承
    PHP三大特性-封装
    PHP面向对象
    循环语句(2)
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8546264.html
Copyright © 2011-2022 走看看