【Math】數學類問題集合
阿新 • • 發佈:2018-11-10
Leetcode 69. Sqrt(x)
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:
Input: 4 Output: 2
Example 2:
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
實現輸入為非負整數的Sqrt(x)函式。若sqrt(x)不為整數,輸出向下取整。
使用二分法實現。 使用二分法,則迴圈的終止條件為:
1,找到了合適的值
2,越過了邊界條件(兩端互相越過,l<=r)
int mySqrt(int x) { if(x==0 || x==1) return x; // 定義左右邊界 int l = 1, r = x, res; // 當兩端未相遇時,不斷使用二分 while(l <= r){ // 首先得到二分點 int m = l + (r - l)/2; // m==x/m。 即得到了需要的答案m if(m == x / m) return m; // m取大了,右邊界左移 else if(m > x / m) r = m - 1; // m取小了,左邊界右移。同時保留一個記憶res。因為可能正確的根是含小數的,等於是記住整數部分 else{ l = m + 1; res = m; } } return res; }