Description
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
1 | Input: 4 |
Example 2:
1 | Input: 8 |
解法
这道题就是自己实现开方的函数,最开始的想法是硬碰撞,从0一直试到x/2+1,如果出现了乘积大于等于结果的情况则返回值,这里需要注意整型数范围问题,所以乘积用long型数表示
具体代码如下:
1 | class Solution { |
然后看到网上的思路发现还可以用二分法解:
1 | class Solution { |