LCR 134. Pow(x, n)

解题思路:

分治 快速幂

Java中向下取整n/=2即可

需要结合下图理解,算法就是实现的该过程

java 复制代码
class Solution {
    public double myPow(double x, int n) {
        if(x == 0.0f) return 0.0d;
        long b = n;
        double res = 1.0;
        //例如:2^-5=(1/2)^5
        if(b < 0) {
            x = 1 / x;
            b = -b;
        }
        //分奇偶讨论,为奇数时要多乘一次x
        while(b > 0) {
            //&与运算,例如:5&1=(101&001)=001=1
            if((b & 1) == 1) res *= x;
            //x=x^2
            x *= x;
            //指数地板除2(b/=2也可以)
            b >>= 1;
        }
        return res;
    }
}
相关推荐
一点事12 小时前
ruoyi:集成mybatisplus实现mybatis增强
java·开发语言·mybatis
e***877012 小时前
Tomcat Request Cookie 丢失问题
java·tomcat·firefox
hweiyu0012 小时前
数据结构:数组
数据结构·算法
linksinke12 小时前
Mapstruct引发的 Caused by: java.lang.NumberFormatException: For input string: ““
java·开发语言·exception·mapstruct·numberformat·不能为空
无限进步_12 小时前
C语言单向链表实现详解:从基础操作到完整测试
c语言·开发语言·数据结构·c++·算法·链表·visual studio
初夏睡觉12 小时前
循环比赛日程表 题解
数据结构·c++·算法
likuolei12 小时前
Eclipse 代码模板
java·ide·eclipse
好好研究12 小时前
SpringMVC框架 - 异常处理
java·开发语言·spring·mvc
只会写代码12 小时前
JDK8 Lambda 加持:打造优雅通用的对象构建器
java
派大星爱吃鱼13 小时前
素数检验方法
算法