[Leetcode] Sqrt(x)

来源:互联网 发布:东北大学奥鹏网络教育 编辑:程序博客网 时间:2024/06/10 17:07

题目:

Implement int sqrt(int x).

Compute and return the square root of x.


思路:二分法,注意溢出,需要将乘积换成long long型。


class Solution {public:    int sqrt(int x) {        if (x < 0) return -1;        long long lower_bound = 0;        long long upper_bound = x;        long long target = x;        while (lower_bound <= upper_bound) {            long long mid = (lower_bound + upper_bound) / 2;            long long temp_product = mid * mid;            if (temp_product == target ||                (temp_product < target && (mid + 1) * (mid + 1) > target)) {                return (int)mid;            } else if (temp_product < x) {                lower_bound = mid + 1;            } else {                upper_bound = mid - 1;            }        }    }};


总结:复杂度O(log n).

0 0
原创粉丝点击