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

边栏推荐
猜你喜欢

RESTful style (detailed introduction + case implementation)

鲁大师7月新机性能/流畅榜:骁龙8+正面对决天玑9000+,性能跑分突破123万!

FreeRTOS实验--删除任务

Seata分布式事务

Introduction to Scala Basic Syntax (3) Various Operators in Scala

鲁大师7月新机性能/流畅榜:性能跑分突破123万!

Singleton pattern of seven kinds of writing, you know?

短视频美食自媒体怎么做?5步教你快速上手

Closures in JS

路由-嵌套路由
随机推荐
高效代码静态测试工具Klocwork 2022.2——Portal全新升级、支持RLM
The uniapp/applet onload method executes the interpretation every time the page is opened
FreeRTOS--优先级实验
百日刷题计划 ———— DAY1
国产 GPU 创业潮 喧嚣下的资本游戏
Introduction to Scala Basic Syntax (3) Various Operators in Scala
This binding to detailed answers
[typescript] Use the RangePicker component in antd to implement time limit the previous year (365 days) of the current time
0801~ Interview questions
[b01lers2020]Welcome to Earth-1
FreeRTOS--栈实验
There are several ways to jump to js source code, jump on the current page, jump on the blank page
机器人碰撞检测方法形式化
无线振弦采集仪远程修改参数方式
js数组递归使用
LeetCode_377_Combination Sum IV
3 ways for OpenFeign to set headers
Singleton pattern of seven kinds of writing, you know?
为什么IDEA连接mysql Unable to resolve table 编译报错但是可以运行
你知道图论的spfa吗?