69. Sqrt(x)
Implement
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
這題我只想到暴力解,所以就直接放棄看解答了,解法非常有趣
用BFS,不斷逼近正確的區段,因為有可能不是整數,最後確定數值是用 if(mid+1 > x/(mid+1)) 來判斷 (來確定下個值會過大,正解就是這個值)
Implement
int sqrt(int x).Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
這題我只想到暴力解,所以就直接放棄看解答了,解法非常有趣
用BFS,不斷逼近正確的區段,因為有可能不是整數,最後確定數值是用 if(mid+1 > x/(mid+1)) 來判斷 (來確定下個值會過大,正解就是這個值)
