当前位置:网站首页>数值的整数次方
数值的整数次方
2022-08-02 13:04:00 【龙崎流河】
题目:
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
示例一:
输入:x = 2.00000, n = 10
输出:1024.00000
示例二:
输入:x = 2.10000, n = 3
输出:9.26100
示例三:
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25
分析:
介绍下快速幂算法,幂运算的指数要么是奇数,要么是偶数,如果是偶数就可以对半拆,如果是奇数就先拎出来一个底数再对半拆。
该题利用快速幂算法思想
代码:
public class MyPow {
public double myPow(double x,int n){
double res = 1;
//把n化为二进制数
long y = n;
if (n < 0){
y = -y;
x = 1/x;
}
while (y > 0){
if (y % 2 == 1){
res = res * x;
}
x = x * x;
y = y / 2;
}
return res;
}
}
边栏推荐
- Closures in JS
- “二舅”火了,自媒体短视频“爆火”的基本要素,你知道吗?
- To eliminate air bubbles to save the mushroom h5 small game source code
- 如何通过DBeaver 连接 TDengine?
- RISC-V instruction format and 6 basic integer instructions
- 吾爱第三课-修改版权和资源
- 单例模式的七种写法,你都知道吗?
- Get out of the machine learning world forever!
- [typescript] Use the RangePicker component in antd to implement time limit the previous year (365 days) of the current time
- js数组递归使用
猜你喜欢
随机推荐
智能手表前景如何?
Enterprise Network Planning Based on Huawei eNSP
Closures in JS
WeChat applet getPhoneNumber interface code=40013
你知道图论的spfa吗?
RISC-V 指令格式和6种基本整数指令
Set proxy server (Google+IE) "Recommended Collection"
js源码跳转的几种方式,在当前页面跳转,在空白页跳转
为什么IDEA连接mysql Unable to resolve table 编译报错但是可以运行
【C语言】剖析函数递归(1)
RestTemplate use: set request header, request body
企业用直播平台能实现什么
UAC绕过学习-总结
Introduction to Graph Neural Networks (GNN) "Recommended Collection"
js cool dashboard plugin
Name conventions in FreeRTOS
Win11怎么修改关机界面颜色?Win11修改关机界面颜色的方法
Get out of the machine learning world forever!
【C语言】手撕循环结构 ——do...while语句及循环练习题(1)
Introduction to Scala Basic Syntax (3) Various Operators in Scala