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

边栏推荐
- FreeRTOS--栈实验
- 【C语言】手把手带你写游戏 —— 猜数字
- 暑假集训-week2图论
- 图论之Floyd,多源图最短路如何暴力美学?
- SQL Server database generation and execution of SQL scripts
- [b01lers2020]Welcome to Earth-1
- SQL Server 2014 installation tutorial (nanny-level graphic tutorial)
- Taurus.MVC V3.0.3 microservice open source framework released: Make the evolution of .NET architecture easier in large concurrency.
- 【C语言】细品分支结构——if-else语句
- scrapy框架初识1
猜你喜欢
随机推荐
.Net 5.0 Quick Start Redis
Js scratchable latex style draw plug-in
图神经网络(GNN)的简介「建议收藏」
Get out of the machine learning world forever!
【C语言】虐打循环结构练习题
RestTemplate 使用:设置请求头、请求体
This binding to detailed answers
qt 编译报错 No rule to make target
网络流详解(流网图一般能够反映什么信息)
js stopwatch countdown plugin
String concatenation in SQL
sql concat() function
photo-sphere-viewer Chinese documentation
瀑布流式布局怎么实现(什么是瀑布流布局)
[typescript] Use the RangePicker component in antd to implement time limit the previous year (365 days) of the current time
86.(cesium之家)cesium叠加面接收阴影效果(gltf模型)
RestTemplate use: set request header, request body
永远退出机器学习界!
Seata分布式事务
js数组递归使用









