博客
关于我
leetcode题解50-Pow(x,n)
阅读量:799 次
发布时间:2023-01-31

本文共 1740 字,大约阅读时间需要 5 分钟。

要实现pow(x, n)函数,我们需要考虑很多特殊情况和优化点。

特殊情况处理

  • n为0:不管x是什么,结果都是1。
  • n为正偶数:结果为正数。
  • x为0:当n>0,结果为0。
  • 代码逻辑

    public class Solution {    public double myPow(double x, int n) {        // 处理n为0的情况        if (n == 0)            return 1.0;        // 处理x为-1的情况        if (Math.Abs(x) == 1.0) {            if ((x > 0) && (n % 2 == 0))                return 1.0;            if (x < 0 && (n % 2 != 0))                return -1.0;            return 1.0;        }        // 处理x为1的情况        if (Math.Abs(x) == 1.0) {            return x == 1.0 ? 1.0 : -1.0;        }        // 处理微小的浮点数误差        if ((x > 1.0 && x < 2.0) || (x < -1.0 && x > -2.0)) {            // 特殊处理接近于1的值            if ((n > 0 && x == 1.0) || (n < 0 && x == -1.0)) {                return 1.0;            }        }        // 处理n为正数的情况        if (n > 0) {            double result = x;            int m = n;            // 逐步计算,避免数值过大导致溢出的问题            do {                result *= x;                // 检查结果是否趋近于0                if (result < 1.0 / 1024.0)                    return 0.0;            } while (m-- > 0);            return result;        } else {            // 处理n为负数的情况            int m = -n;            do {                try {                    result *= result;                    // 检查是否结果趋近于0                    if (result < 1.0 / 1024.0)                        return 0.0;                } catch (OverflowException) {                    // 检查结果是否会溢出                    if (result > 1.7976931348623157e+308)                        return 0.0;                }            } while (m-- > 0);            // 取倒数            return 1.0 / result;        }    }}

    优化点

    • 数字处理:当计算结果趋向于0时,提前终止循环。
    • 避免溢出:使用双精度数并检查计算结果是否接近最大值。
    • 特殊值处理:快速处理x为1和-1的情况,以及n为0的情况,确保代码高效运行。
    • 减少循环次数:通过对数运算或者位处理,减少循环次数,提高性能。

    转载地址:http://pegyk.baihongyu.com/

    你可能感兴趣的文章
    PostgreSQL Oracle 兼容性之 - pipelined
    查看>>
    PostgreSQL Point-In-Time Recovery (Incremental Backup)
    查看>>
    postgresql Streaming Replication监控与注意事项
    查看>>
    postgresql 不需要付费_使用数据传输在PostgreSQL执行 外部连接运算符
    查看>>
    postgresql 主从配置_生产环境postgresql主从环境配置
    查看>>
    postgresql 函数&存储过程 ; 递归查询
    查看>>
    PostgreSQL 分组聚合查询中 filter 子句替换 case when
    查看>>
    PostgreSQL 同步流复制锁瓶颈分析
    查看>>
    PostgreSQL 备份与还原命令 pg_dump
    查看>>
    Postgresql 外部表插件postgres_fdw的安装和使用
    查看>>
    PostgreSQL 如何从崩溃状态恢复(上)
    查看>>
    PostgreSQL 存储过程基本语法
    查看>>
    PostgreSQL 实现批量更新、删除、插入
    查看>>
    PostgreSQL 导入 .gz 备份文件
    查看>>
    PostgreSQL 批量插入&更新数据时报错(ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time)
    查看>>
    PostgreSQL 新增数据返回自增ID
    查看>>
    postgresql 更新多列数据
    查看>>
    PostgreSQL 服务启动后停止
    查看>>
    PostgreSQL 辟谣存在任意代码执行漏洞:消息不实
    查看>>
    PostgreSQL+PostGIS实现两坐标点之间最短路径查询算法函数(地图工具篇.12)
    查看>>