当前位置:网站首页>数值的整数次方
数值的整数次方
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;
}
}

边栏推荐
- 移动端适配,华为浏览器底色无法正常显示
- "Second Uncle" is popular, do you know the basic elements of "exploding" short videos from the media?
- WeChat applet getPhoneNumber interface code=40013
- In-depth analysis and use of Ribbon load balancing
- FreeRTOS--栈实验
- 路由-Tab切换页面
- SQL Server 2014 installation tutorial (nanny-level graphic tutorial)
- WPF效果第一百九十三篇之登录实现
- js stopwatch countdown plugin
- [b01lers2020]Welcome to Earth-1
猜你喜欢

Mysql视图

Get out of the machine learning world forever!

节省50%成本!京东云重磅发布新一代混合CDN产品

图论之Kruskal,最小生成树如何优雅解题?
![[C language] Analysis of function recursion (1)](/img/9c/298c347ad87dedf55e020f5d8321c7.png)
[C language] Analysis of function recursion (1)

Closures in JS

Enterprise Network Planning Based on Huawei eNSP

In-depth analysis and use of Ribbon load balancing

To eliminate air bubbles to save the mushroom h5 small game source code

Win11怎么修改关机界面颜色?Win11修改关机界面颜色的方法
随机推荐
国产 GPU 创业潮 喧嚣下的资本游戏
Singleton pattern of seven kinds of writing, you know?
【C语言】函数哪些事儿,你真的get到了吗?(2)
【C语言】夏日一题 —— 求最大公约数和最小公倍数
80篇国产数据库实操文档汇总(含TiDB、达梦、openGauss等)
FreeRTOS--Priority Experiment
自动生成代码器推荐-code-gen
js源码跳转的几种方式,在当前页面跳转,在空白页跳转
MFC入门教程(深入浅出MFC)
Four seasons of trees realized by svg
Introduction to Scala Basic Syntax (3) Various Operators in Scala
uniapp/小程序 onload方法每次打开页面都执行解读
[b01lers2020]Welcome to Earth-1
UAC绕过学习-总结
PGSQL database to realize the import and export
Win11怎么修改关机界面颜色?Win11修改关机界面颜色的方法
js array recursively use
Seata分布式事务
Intouch System Platform IDE-1
汉源高科千兆12光12电管理型工业以太网交换机 12千兆光12千兆电口宽温环网交换机