/** *题目:实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题 *时间:2015年8月28日10:48:28 *文件:MyPow.java *作者:cutter_point */ package bishi.Offer50.y2015.m08.d28; import org.junit.Test; public class MyPow { /** * 求一个数的exponent次方 * @param base * @param exponent * @return */ public double power(double base, int exponent) { if(this.equal(base, 0.0)) return 0; else if(this.equal(exponent, 0.0)) return 1; int absExponent = exponent; boolean isFu = false; //是否是负数 if(exponent < 0) { isFu = true; absExponent = -exponent; }//if double result = absPower(base, absExponent); if(isFu) { result = 1 / result; }//if return result; } /** * 当指数是正数的时候 * @param base * @param absExponent * @return */ public double absPower(double base, int absExponent) { double result = 1.0; for(int i = 1; i <= absExponent; ++i) result *= base; return result; } /** * 更快的算法 * @param base * @return */ public double absPower2(double base, int absException) { if(absException == 0) return 1; else if(absException == 1) return base; double result = absPower2(base, absException >> 1); result *= result; //判断奇偶 if((absException & 0x1) == 1) { result *= base; } return result; } /** * 计算机中单纯的result == 0并不能好好判断这两个数是否一样,float和double类型的数在计算机中表示是有误差的 * @param num1 * @param num2 * @return */ public boolean equal(double num1, double num2) { double result = num1 - num2; if(result < 0.0000001 && result > -0.0000001) { return true; } else return false; } public static void test(double base, int exponent) { MyPow mp = new MyPow(); double time1 = System.currentTimeMillis(); System.out.println(mp.power(base, exponent)); double time2 = System.currentTimeMillis(); System.out.println("运行时间:" + (time2 - time1)); System.out.println(mp.absPower2(base, exponent)); double time3 = System.currentTimeMillis(); System.out.println("运行时间:" + (time3 - time2)); } @Test public void test1() { test(0, 10); } @Test public void test2() { test(65, 10); } public static void main(String[] args) { // TODO Auto-generated method stub } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/cutter_point/article/details/48049633