剑指Offer面试题11 & Leetcode50
来源:互联网 发布:ps调色插件 知乎 编辑:程序博客网 时间:2024/05/16 06:31
剑指Offer面试题11 & Leetcode50
Pow(x, n) 数值的整数次方
Implement pow(x, n).
解题思路
考虑:这个题的难点在于处理各种极端输入,例如指数为0,指数为负等,需要考虑全面。在实现乘方的过程中,使用递推关系式减小乘法次数,缩短运行时间。
递推公式为:n为偶数时,a的n次方等于a的n/2次方乘a的n/2次方。n为奇数时,a的n次方等于a的n/2次方乘a的n/2次方乘a。
Solution
public double myPow(double x, int n) { if(x == 0.0 && n == 0) return 0.0; if(x == 1.0) return 1.0; boolean isPositive = true; if(n < 0){ isPositive = false; n = -n; System.out.println(n); } if(n == Integer.MIN_VALUE){ double result = 1.0/(powerWithUnsigned(x,Integer.MAX_VALUE) * x); return result; } double result = powerWithUnsigned(x,n); if(!isPositive){ result = 1.0/result; } return result; } double powerWithUnsigned(double x, int n){ if(n == 0){ return 1; } if(n == 1){ return x; } double result = powerWithUnsigned(x,n>>1); result *= result; if((n & 1) == 1){ result *= x; } return result; }
0 0
- 剑指Offer面试题11 & Leetcode50
- 剑指Offer 面试题11:数的整数次方(Leetcode50. Pow(x, n))【C库函数pow模拟】题解
- 剑指offer面试题11
- 剑指offer 面试题11
- 剑指offer面试题11
- 剑指offer 面试题
- 剑指offer面试题
- 剑指Offer(面试题11-13)
- 剑指offer刷题---面试题11
- 剑指offer面试题总结
- 剑指offer面试题06
- 剑指offer面试题 04
- 剑指offer 面试题07
- 剑指offer面试题08
- 剑指offer面试题42
- 剑指offer面试题1
- 剑指offer面试题3
- 剑指offer面试题4
- Android 状态选择器
- double占几个字节
- Ogre2.1 分析笔记(五) 渲染流程(二)
- 从github删除一个repository
- js作用域之js编译
- 剑指Offer面试题11 & Leetcode50
- 远程调用服务器方法:POST方法
- 你是「空巢程序员」吗?
- Android开发工具类常用
- Mysql数据库巩固
- 怎么把F1-F12的功能按键模式修改为传统的单键快捷按键模式。
- Android 自己封装HttpUrlConnection上传图片和字段
- 值传递和引用传递的区别
- Angular2如何整合其他插件