1. 程式人生 > >LeetCode 69. Sqrt(x)(x的算術平方根)

LeetCode 69. Sqrt(x)(x的算術平方根)

題目描述:

    Implement int sqrt(int x).
    Compute and return the square root of x.
    x is guaranteed to be a non-negative integer.

例子:

Input: 4
Output: 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.

分析:
    題意:給定一個非負整型數x,返回x的算術平方根。

    思路:此題採用二分法。因為x的算術平方根屬於1→x 之間,所以我們初始化指標left = 1,right = x,則mid = left + (right - left) >> 1,我們需要判斷mid * mid和x的大小。注意一點:當正整型數(int)mid足夠大時,mid * mid運算可能會溢位,因此我們臨時把mid和x轉化為長整型數(long long int)進行比較:① 如果(LL)mid * (LL)mid == (LL)x,則找到算術平方根mid,返回;② 如果(LL)mid * (LL)mid > (LL)x,則mid過大,令right = mid - 1繼續查詢
;③ 如果(LL)mid * (LL)mid < (LL)x,則mid過小,令left = mid + 1繼續查詢
    時間複雜度為O(log(x))。

程式碼:

#include <bits/stdc++.h>

using namespace std;

#define LL long long

class Solution {
public:
    int mySqrt(int x) {
		// Exceptional Case: 
        if(x <= 1){
			return x;
		}
		int left = 1, right = x;
		while(left <= right){
			int mid = left + (right - left) / 2;
			if((LL)mid * (LL)mid == (LL)x){
				return mid;
			}
			else if((LL)mid * (LL)mid > (LL)x){
				right = mid - 1;
			}
			else if((LL)mid * (LL)mid < (LL)x){
				left = mid + 1;
			}
		}
		return right;
    }
};