一、题目内容

image.png

二、题解

解法1:

思路

快速降幂法

  • x的n次方=x平方的n/2次方
  • 同时要注意,当n为负数时,需要返回1/x的-n次方
  • int的负数最大值直接取反会移除,所以可以用long接一下

    代码

    1. class Solution {
    2. public double myPow(double x, int n) {
    3. if (x == 0) {
    4. return 0d;
    5. }
    6. long exp = n;
    7. double res = 1.0;
    8. if (exp < 0) {
    9. x = 1 / x;
    10. exp = -exp;
    11. }
    12. while (exp > 0) {
    13. if (exp % 2 == 1) {
    14. res *= x;
    15. }
    16. x *= x;
    17. exp /= 2;
    18. }
    19. return res;
    20. }
    21. }