69. Sqrt(x)
Question:
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Example:
Input: x = 4
Output: 2
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
Source Code
Version 1
Idea:
My intuition is divided divisor that is start from 1, we can get remainder, if remainder is equal to divisor, return the divisor; if divisor is bigger than remainder, retrurn the (divisor - 1).
This method can work, but it wastes much time.
Time complexity: O(sqrt(x))
Space complexity: O(1)
1 | class Solution { |
Version 2
Idea:while(l <= r)
can filter x = 0
test case. We use m * m
to find which value can match x.
Time complexity: O(logn)
Space complexity: O(1)
1 | class Solution { |