前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Math - 50. Pow(x, n)

Math - 50. Pow(x, n)

作者头像
ppxai
发布2020-09-23 17:45:33
2850
发布2020-09-23 17:45:33
举报
文章被收录于专栏:皮皮星球
  1. Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

代码语言:javascript
复制
Input: 2.00000, 10
Output: 1024.00000

Example 2:

代码语言:javascript
复制
Input: 2.10000, 3
Output: 9.26100

Example 3:

代码语言:javascript
复制
Input: 2.00000, -2
Output: 0.25000
Explanation: 2^-2 = 1/22 = 1/4 = 0.25

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [−231, 231 − 1]

思路:

题目是让实现幂次计算,做法是把幂次分解,分解到0,然后乘起来,比如5^3 = 5^1 * 5^1 * 5^1 = (5^0 * 5^0 * 5^1) * (5^0 * 5^0 * 5^1)

代码:

go:

代码语言:javascript
复制
func myPow(x float64, n int) float64 {
    if n > 0 {
        return pow(x, n)
    } else {
        return 1.0 / pow(x, n)
    }
}

func pow(x float64, n int) float64 {
    if n == 0 {
        return 1
    }
    
    y := pow(x, n/2)
    if n % 2 == 0 {
        return y * y
    } else {
        return y * y * x
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020年05月17日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档