import java.util.*;
public class Solution {
/**
*
* @param x int整型
* @return int整型
*/
public int sqrt (int x) {
if(x<=0) return 0;
long left = 1,right = x;
while(left<right){
long mid = (left+right)/2;
if(mid*mid<=x&&(mid+1)*(mid+1)>x){
return (int)mid;
}else if(mid*mid>x){
right = mid;
}else{
left = mid;
}
}
return (int)left;
}
}
常规思路:从零开始遍历,如果当前值的平方<=x 且 下一个值的平方 > x 则 当前值即为要找的值
import java.util.*;
public class Solution {
public int sqrt (int x) {
if(x<=0) return 0;
if(x==1) return 1;
for(int i=0;i<x;i++){
if(i*i<=x&&(i+1)*(i+1)>x){
return i;
}
}
return 0;
}
}