[Leetcode] Sqrt(x)

Sqrt(x) 题解

题目来源:https://leetcode.com/problems/sqrtx/description/


Description

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example

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.

Solution

class Solution {
public:
    int mySqrt(int x) {
        if (x == 0)
            return 0;
        if (x <= 3)
            return 1;
        int low = 2;
        int high = x / 2;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (mid > x / mid) {
                high = mid;
            } else if (mid + 1 <= x / (mid + 1)) {
                low = mid;
            } else {
                return mid;
            }
        }
    }
};


解题描述

这道题是要实现一个开平方根的函数,且返回值是平方根进行截断后的整数部分,这里考虑的做法是二分查找,针对输入数字大于4的情况,下界定为2,上界定位输入数的一半。

posted @ 2018-02-02 13:19  言何午  阅读(114)  评论(0编辑  收藏  举报