50. Pow(x, n) (JAVA)
2024-08-28 05:07:11
Implement pow(x, n), which calculates x raised to the power n(xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [−231, 231 − 1]
通过二分法,通过平方,减少乘法的次数。
注意指数是负数的情况。
class Solution {
public double myPow(double x, int n) {
if(n==0) return 1; double result = myPow(x, n/2);
result *= result;
if(n%2 == 1) result *= x;
else if(n%2==-1) result = (1/x) * result; //negative number
return result;
}
}
最新文章
- HTML5的Audio标签打造WEB音频播放器
- RS232,RS422串口标准小结
- jQuery事件笔记
- Python语言and-or的用法
- jquery.datepair日期时分秒选择器
- Codeforces Round #346 (Div. 2)E - New Reform(DFS + 好题)
- C++实现数字媒体三维图像渲染
- qsort函数的简单实践
- spring 入门篇
- java 读取excel(Map结构)xls
- bzoj2049
- w7如何安装配置多个tomcat
- 网络协议中HTTP,TCP,UDP,Socket,WebSocket的优缺点/区别
- Idea自带工具解决冲突
- Mac 建PHP 环境 及 配置 apache 默认目录
- yum报错:Error: Multilib version problems found. This often means that the root
- docker知识点
- Linux命令(九)比较文件差异 diff
- UserInfoActivity用户图像修改和退出登录
- Windows Git Bash命令行下创建git仓库并更新到github