剑指offer-数值的整数次方
数值的整数次方
http://www.nowcoder.com/questionTerminal/1a834e5e3e1a4b7ba251417554e07c00
题目描述:
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
解法一:
public class Solution { public double Power(double base, int exponent) { if(exponent < 0){ base = 1 / base; exponent = -exponent; } return fastpow(base,exponent); } public double fastpow(double b, int n){ if(n == 0){ return 1.0; } double tmp = fastpow(b,n/2); if((n & 1) == 1){ return tmp * tmp * b; }else{ return tmp * tmp; } } }
运行时间:29ms;占用内存:10672KB
解法二:
public class Solution { public double Power(double base, int exponent) { if(base == 0) return 0; if(exponent == 0) return 1.0; if(exponent < 0){ return Power(1/base, -exponent); } double cur = base; double res = 1.0; while(exponent > 0){ if((exponent & 1) == 1){ res = res * cur; } cur = cur * cur; exponent >>= 1; } return res; } }
运行时间:27ms;占用内存:10576KB