题目
题目链接:
https://www.nowcoder.com/practice/09fbfb16140b40499951f55113f2166c
思路
Java代码
import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param x int整型* @return int整型*/public int sqrt (int x) {if (x <= 1) return x;int L = 0, R = x, ans = -1;while (L <= R) {int mid = L + (R - L) / 2;if ((long)mid * mid <= x) {ans = mid;L = mid + 1;} else {R = mid - 1;}}return ans;}
}
Go代码
package main/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param x int整型* @return int整型*/
func sqrt(x int) int {if x <= 1 {return x}L := 1R := xans := -1for L <= R {mid := L + (R-L)/2if mid*mid <= x {ans = midL = mid + 1} else {R = mid - 1}}return ans
}
C++ 代码
class Solution {
public:/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param x int整型 * @return int整型*/int sqrt(int x) {if(x<=1) return x;int L=1,R=x,ans=-1;while(L<=R){int mid = L+(R-L)/2;if((long long)mid*mid <=x){ans =mid;L=mid+1;}else{R=mid-1;}}return ans;}
};