学习时间:
2023年1月28日
题目描述:

题解分享:
/**
* @ Author 繁华倾夏
* @ Date 2023年01月28日
*/
// 力扣(LeetCode):69. x 的平方根
public class Solution {
// 方法一:数学分析
public static int mySqrt1(int x) { // 调用函数
if (x == 0) { // 当为0时返回
return 0;
}
int ans = (int) Math.exp(0.5 * Math.log(x)); // 利用对数公式
return (long) (ans + 1) * (ans + 1) <= x ? ans + 1 : ans; // 判断范围
}
// 方法二:理论分析
public static int mySqrt2(int x) { // 调用函数
long i; // 数值范围大所以,要设定为长整型,防止溢出
for(i=0;i<=x;i++){ // 遍历即可
if(i*i==x){
return (int)i; // Java中函数的类型是int
} // 需要强制类型转换
if(i*i>x){
return (int)(i-1);
}
}
return 0;
}
// 测试用例
// 输入 x = 4
// 输出 2
public static void main(String[] args) {
int x=2147483647;
int re1=mySqrt1(x);
int re2=mySqrt2(x);
System.out.println(re1);
System.out.println(re2);
}
}
【繁华倾夏】【每日力扣题解分享】【Day14】