当前位置:网站首页>数值的整数次方
数值的整数次方
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;
}
}
边栏推荐
猜你喜欢
Introduction to Scala Basic Syntax (3) Various Operators in Scala
How to use the database like tap water?|Tencent Cloud Database TDSQL-C
微信小程序getPhoneNumber接口code=40013
[C language] Analysis of function recursion (1)
【C语言】剖析函数递归(1)
【C语言】函数哪些事儿,你真的get到了吗?(2)
如何通过DBeaver 连接 TDengine?
【C语言】夏日一题 —— 求最大公约数和最小公倍数
PHP+MYSQL [Student Information Management System] (Minimalist Edition)
Seata分布式事务
随机推荐
Interpretation of new features | MySQL 8.0 GIPK invisible primary key
0801~ Interview questions
水平垂直居中方式
第48篇-timestamp2参数分析【2022-08-01】
[typescript] Use the RangePicker component in antd to implement time limit the previous year (365 days) of the current time
LeetCode_139_word split
Seata Distributed Transaction
工厂方法模式
How to implement waterfall flow layout (what is waterfall flow layout)
RESTful 风格(详细介绍 + 案例实现)
Object.entries()
FreeRTOS experiment -- delete task
【C语言】虐打循环练习题(2)
【C语言】虐打循环结构练习题
Js scratchable latex style draw plug-in
嵌入式系统驱动初级【2】——字符设备驱动基础上_基础框架
Mysql索引详解(图文并茂)
【C语言】手把手带你写游戏 —— 猜数字
高效代码静态测试工具Klocwork 2022.2——Portal全新升级、支持RLM
什么是 commonjs2