buuctf crypto 【密码学的心声】解题记录

阅读 82

2023-09-17

题目

实现 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
  • n 是一个整数
  • 要么 x 不为零,要么 n > 0 。
  • -104 <= xn <= 104

代码

class Solution {
public static double myPow(double x, int n) {
long N=n;
return n<0 ? 1/calculate(x,-N):calculate(x,N);
}
public static double calculate(double x,long n)
{
if(n==0)
{
return 1;
}
double res=calculate(x, n/2);
return n%2==1 ? res*res*x : res*res;
}
public static void main(String[] args) {
double n = 2.5;
int x = 3;
double result = myPow(n, x);
System.out.println(n + " 的 " + x + " 次幂是: " + result);
}
}

 

精彩评论(0)

0 0 举报