题目:
Implement int sqrt(int x)
.
Compute and return the square root of x.
题意:
实现int sqrt(int x)函数。计算并返回x的平方根。
思路一:
二分法搜索,每次对1到x的中间值进行判断。
代码:C++版:0ms
class Solution { public: int mySqrt(int x) { if (x<=1) return x; int left = 1, right = x; while (left < right) { int mid = left + (right - left)/2; if (mid <= x/mid) { left = mid + 1; } else { right = mid; } } return left - 1; } };
思路二:
利用位操作计算sqrt(x)算法。
代码:java版:2ms
public class Solution { public int mySqrt(int x) { long ans = 0; long bit = 1l << 16; while (bit > 0) { ans |= bit; if (ans * ans > x) { ans ^= bit; } bit >>= 1; } return (int)ans; } }