当前位置:网站首页>数值的整数次方
数值的整数次方
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;
}
}
边栏推荐
- 【622. 设计循环队列】
- RISC-V 指令格式和6种基本整数指令
- js数组递归使用
- SQL Server database generation and execution of SQL scripts
- PGSQL database to realize the import and export
- SQL Server 2019 installation error 0 x80004005 service there is no timely response to the start or control request a detailed solution
- js源码跳转的几种方式,在当前页面跳转,在空白页跳转
- 自动生成代码器推荐-code-gen
- FreeRTOS实验--删除任务
- PHP+MYSQL [Student Information Management System] (Minimalist Edition)
猜你喜欢
How to create short images and short videos from the media?How to make the click volume reach 10W?
To eliminate air bubbles to save the mushroom h5 small game source code
"Second Uncle" is popular, do you know the basic elements of "exploding" short videos from the media?
wx-wow(微信小程序动效库)
ETL(二):表达式组件的使用
【C语言】手撕循环结构 ——do...while语句及循环练习题(1)
A powerful js pop-up alert plugin
Ribbon负载均衡的深度分析和使用
【C语言】函数哪些事儿,你真的get到了吗?(2)
First acquaintance of scrapy framework 1
随机推荐
【C语言】虐打循环练习题(2)
How to turn off hardware acceleration [easy to understand]
Seata Distributed Transaction
How to create short images and short videos from the media?How to make the click volume reach 10W?
Mysql视图
最小割和对偶图(未完成)
吾爱第三课-修改版权和资源
Four seasons of trees realized by svg
定了!2022世界VR产业大会将继续在南昌召开
package.json and package-lock.json
Seata分布式事务
Markdown怎么加入emoji
LeetCode_139_word split
国产 GPU 创业潮 喧嚣下的资本游戏
[b01lers2020]Welcome to Earth-1
使用Amazon SageMaker 构建基于自然语言处理的文本摘要应用
RESTful style (detailed introduction + case implementation)
js true 3d histogram plugin
Article 48 - Analysis of timestamp2 parameters【2022-08-01】
Openlayers Quick Start Tutorial