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

    Implement pow(xn).

    double sum = 1;
    		if (n > 0) {
    			while ((n--) > 0)
    				sum *= x;
    			return sum;
    		} else if (n < 0) {
    			while ((n++) < 0)
    				sum /= x;
    		}
    		return sum;  //开始单纯的我是这样写的。超时了
    

      

    	if (n == 0)           //想了一下,不就是求x+10000/x的最小值。自己运行都通过了,但是leetcode仍然显示超时,错误1,x的100次仍然很大,需要bigdeciml。错误2,前后两步运行时间是相差很大的,所以不是求x+10000/x的最小值。AC版的才是正确答案
    			return 1;
    		double sum = 1, tmp = 1;
    		if (n > 0) {
    			int sq = (int) Math.round(Math.sqrt(n));
    			for (int i = sq; i > 0; i--)
    				tmp *= x;
    			// System.out.println(tmp);
    			for (int i = 0; i < sq; i++)
    				sum *= tmp;
    			int i = n - sq * sq;
    			// System.out.println(i);
    			if (i > 0) {
    				for (int j = 0; j < i; j++)
    					sum *= x;
    			} else if (i < 0) {
    				for (int j = i; j < 0; j++)
    					sum /= x;
    			}
    			return sum;
    		} else {
    			int m = Math.abs(n);
    			int sq = (int) Math.round(Math.sqrt(m));
    			for (int i = sq; i > 0; i--)
    				tmp /= x;
    			// System.out.println("tmp="+tmp);
    			for (int i = 0; i < sq; i++)
    				sum *= tmp;
    			int i = n + sq * sq;
    			// System.out.println(i);
    			if (i > 0) {
    				for (int j = 0; j < i; j++)
    					sum *= x;
    			} else if (i < 0) {
    				for (int j = i; j < 0; j++)
    					sum /= x;
    			}
    			return sum;
    		}
    

      

    public class Solution {            //虽然用了递归,挺巧妙的,一定要记得思想  & 和 >>
      public double myPow(double x, int n) {   //类似思想的还有求最大公约数
      if (n == 0) return 1.0;
      if (n < 0) { x = 1 / x; n = ~n + 1; }
      if (n == 1) return x;
      if (n == 2) return x * x;
      if ((n & 1) == 1) return x * myPow(x * x, n >> 1);
      return myPow(x * x, n >> 1);
    }
    }
    

      

  • 相关阅读:
    Android——继续深造——从安装Android Studio 2.0开始(详)
    PHP——安装wampserver丢失MSVCR110.dll
    Marza Gift for GDC 2016
    Retrieve OpenGL Context from Qt 5.5 on OSX
    Space Time Varying Color Palette
    Screen Space Depth Varying Glow based on Heat Diffusion
    Visualization of Detail Point Set by Local Algebraic Sphere Fitting
    Glass Dragon
    Jump Flood Algorithms for Centroidal Voronoi Tessellation
    京都之行
  • 原文地址:https://www.cnblogs.com/kydnn/p/5163726.html
Copyright © 2011-2022 走看看