Skip to content

[剑指 Offer] 16. 数值的整数次方 #53

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Jul 30, 2021 · 0 comments
Open

[剑指 Offer] 16. 数值的整数次方 #53

frdmu opened this issue Jul 30, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Jul 30, 2021

实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。

 

示例 1:

输入:x = 2.00000, n = 10
输出:1024.00000

示例 2:

输入:x = 2.10000, n = 3
输出:9.26100

示例 3:

输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25

 

提示:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • -104 <= xn <= 104
     

解法:
快速幂。
1
数学技巧。代码如下:

class Solution {
public:
    double myPow(double x, int n) {
        if (n==0) return 1.0;
        unsigned int m = n; 
        if (n < 0) {
            m = ~m + 1;
            x = 1/x;
        } 
        double res = 1.0;
         
        while (m) {
            if (m&1) {
                res *= x;
            } 
            x *= x;
            m = m >> 1;
        }
        
        return res;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant