50. Pow(x, n)
2016-12-11 21:41
197 查看
Implement pow(x, n).
幂运算
直接乘需要n-1次自乘,使用递归可以减少很多次乘法运算。
public class Solution {
public double myPow(double x, int n) {
double t=n;
if(t<0){
x=1/x;
t=-t;
}
if(t==0)
return 1;
if(t==1)
return x;
if(t%2==0)
return myPow(x*x,(int)t/2);
else
return myPow(x*x,(int)t/2)*x;
}
}
幂运算
直接乘需要n-1次自乘,使用递归可以减少很多次乘法运算。
public class Solution {
public double myPow(double x, int n) {
double t=n;
if(t<0){
x=1/x;
t=-t;
}
if(t==0)
return 1;
if(t==1)
return x;
if(t%2==0)
return myPow(x*x,(int)t/2);
else
return myPow(x*x,(int)t/2)*x;
}
}
相关文章推荐
- 神经网络与深度学习(3):Backpropagation算法
- Linux电源管理-Runtime PM
- 1080. Graduate Admission (30)
- 郝斌的C语言基础 165,166 枚举
- CentoOS更换yum源
- [SSH]如何敲一条线
- 走进阿里,从提高自身开始
- 【工具】让开发更高效-Firefox Developer Edition
- 《Android群英传》---读书笔记5
- 高性能Mysql主从架构的复制原理及配置详解
- 用HTML中的列表标签做一个导航栏吧
- NG《Machine_Learning_Yearning》笔记
- [RegEx]识别路径中是否有本地盘符
- 漫漫考研路之C语言的位运算
- 124. Binary Tree Maximum Path Sum
- Java安装与编程
- 2016年12月9日 课堂笔记
- 互联网服务线上数据迁移的原则和方法
- replace和replaceAll的区别:
- 巧用Snackbar代替Toast