Implement int sqrt(int x).
Compute andreturnthe square root of x, where x is guaranteed to be a non-negative integer.
Since thereturn type is an integer, the decimal digits are truncated and only theinteger part oftheresultis returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of8is2.82842..., andsincethe decimal part is truncated, 2is returned.
提交反馈:
1017 / 1017 test cases passed.
Status: Accepted
Runtime:22 ms
Submitted:0 minutes ago
You are here!
Your runtime beats 80.32 % of java submissions.
解题思路:
二分法。被JAVA的int与long坑了,刚开始提交报错发现int溢出,然后决定改为long,就OK。另外,java没有无符号整数。
理论上,int表示最大2的32次(int占用4个字节),long最大表示2的64次(long占用8个字节),这样2的32次的平方也小于2的64次,不会溢出的啊,懵逼。。。经查询,发现这个long是带符号的,并且java没有无符号的整数。。。
参考链接:[java中 long 和double的区别](https://blog.csdn.net/qq_34789775/article/details/71153161)
还有一种思路就是:
不要写成middle*middle==x,会溢出
写成这样的,if(middle==x/middle)
代码:
class Solution {
publicintmySqrt(int x) {
if(x == 0){
return0;
}
if(x == 1){
return1;
}
long left = 1;
long right = x;
double middle; //不能为int或者long,因为long为无符号整数,当x很大时候会出现负数。while(right - left > 1){
middle = (left + right)/2;
double dot = middle * middle;
if(dot > x){
right = (long)middle;
}
elseif(dot < x){
left = (long)middle;
}
else{
return (int)middle;
}
}
return (int)left;
}
}