LeetCode做题笔记 - 69 - X的平方根(简单)

题目:求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.

思路

只用精确到整数(直接舍弃小数,不是四舍五入)。用二分法搜索。取x的一半x/2,求x/2的平方,跟x比较。如果小,则继续在后半部分搜索;如果大,则继续在前半部分搜索;相等则直接返回。
考虑到算平方的时候,可能超出int范围,因此用double。

代码

class Solution {
public:
    int mySqrt(int x) {
        if (x == 0) return 0;
        if (x < 4) return 1; // 较小的情况直接返回,避免二分出错
        int lower = 0;
        int higher = x;
        while (higher > lower+1)  // 结束循环的条件是搜索范围变为1
        {
            double mid = (higher + lower) / 2;
            if (mid*mid == x)
            {
                return (int)mid;
            }
            else if (mid*mid > x)
            {
                higher = mid;
            }
            else
            {
                lower = mid;
            }
        }
        return lower; // 精确到整数,取较小的
    }
};
posted @ 2019-03-18 17:04  星夜之夏  阅读(154)  评论(0)    收藏  举报