1. 程式人生 > >【LeetCode】112.Sqrt(x)

【LeetCode】112.Sqrt(x)

題目描述(Easy)

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.

題目連結

https://leetcode.com/problems/sqrtx/description/

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.

演算法分析

任何大於1的整數的開平方一定是大於1、小於x/2的,因此可以在[1,x/2]區間內使用二分查詢來查詢這個數。

提交程式碼:

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