LeetCode算法系列:69. Sqrt(x)
阿新 • • 發佈:2018-12-10
目錄
題目描述:
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.
演算法實現
總體的思路是使用二分法,但是用int long這樣的資料型別總是溢位,想了一個辦法,通過一次二分法找到一個小的範圍,再執行二分法
class Solution { public: int mySqrt(int x) { int i = 0, j = x; long long mid = x; long long suanz = 0; while(mid * mid > x)mid = mid/2; i = mid, j = mid * 2; while(i <= j){ mid = (i + j)/2; suanz = mid*mid; if(suanz == x)return mid; else if(suanz > x)j = mid - 1; else if(suanz < x)i = mid + 1; } return j; } };
他山之石:
發現已提交的答案中有類似的做法,不過使用size_t型定義資料
size_t是一些C/C++標準在stddef.h中定義的。這個型別足以用來表示物件的大小。size_t的真實型別與作業系統有關。
在32位架構中被普遍定義為:
typedef unsigned int size_t;
而在64位架構中被定義為:
typedef unsigned long size_t;
size_t在32位架構上是4位元組,在64位架構上是8位元組,在不同架構上進行編譯時需要注意這個問題。而int在不同架構下都是4位元組,與size_t不同;且int為帶符號數,size_t為無符號數。
class Solution {
public:
int mySqrt(int x) {
size_t i = 0, j = x;
size_t mid, suanz;
while(i <= j){
mid = (i + j)/2;
suanz = mid*mid;
if(suanz == x)return mid;
else if(suanz > x)j = mid - 1;
else if(suanz < x)i = mid + 1;
}
return j;
}
};