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

    借鉴了之前加法的超时经验,就开始采用倍增法。但还是吃了负数和整数边界值的亏。最后干脆使用long得了。参考答案的递归果然更简洁易懂,而且不用考虑整数边界值的情况,精彩。

    public class Solution {
        public double pow(double x, int n) {
            // Start typing your Java solution below
            // DO NOT write main() function
            
            double ans = 1;
        	double tmp = x;
            boolean neg = false;
            long m = n;
            if (m < 0) {
                neg = true;
                m = -m;
            }
        	long bound = m;
        	
        	while (bound != 0) {
        		long i = 1;
    	    	for (; i*2 <= bound; i*=2) {
    	    		tmp = tmp * tmp;
    	    	}
    	    	ans *= tmp;
    	    	tmp = x;
    	    	bound = bound - i;
        	}
            
            if (neg) return 1.0 / ans;
        	
        	return ans;
        }
    }
    

    参考答案:http://discuss.leetcode.com/questions/228/powx-n

    double pow(double x, int n) {
        if (n == 0) return 1.0;
        // Compute x^{n/2} and store the result into a temporary
        // variable to avoid unnecessary computing
        double half = pow(x, n / 2);
        if (n % 2 == 0)
            return half * half;
        else if (n > 0)
            return half * half * x;
        else
            return half * half / x;
    }
    

    第二刷:要注意n是负数的情况,还有负到头~

    class Solution {
    public:
        double pow(double x, int n) {
            if (x == 0 || x == 1) return x;
            if (n < 0 && n != INT_MIN) return 1.0 / pow(x, -n);
            if (n == 0) return 1.0;
            double p = pow(x, n / 2);
            if (n % 2 == 0) {
                return p * p;
            } else {
                return p * p * x;
            }
        }
    };
    

      

  • 相关阅读:
    CodeGen用户定义的扩展令牌
    CodeGen编写自定义表达式标记
    CodeGen CreateFile实用程序
    CodeGen融合核心关系循环扩展
    CodeGen融合核心扩展定制文件
    CodeGen API分析
    CodeGen字段循环Field Loop
    CodeGen概述
    算子扫描与递归核
    算子本质与数学函数
  • 原文地址:https://www.cnblogs.com/lautsie/p/3242224.html
Copyright © 2011-2022 走看看