首页 > 其他 > 详细

Sqrt(x)_LeetCode

时间:2017-12-05 20:00:45      阅读:246      评论:0      收藏:0      [点我收藏+]

Description:

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

 

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.

解法一:
一开始没有明白题目的用途,直接调用sqrt函数之后,强制转换成int类型。代码如下:
class Solution {
public:
    int mySqrt(int x) {
        double tmp;
        tmp = floor(sqrt(x));
        int result = 0;
        result = int(tmp);
        return result;
    }
};

 

解法二:

利用二分法查找,代码如下:

class Solution {
public:
    int mySqrt(int x) {
        long long left = 0; //为了防止平方过程出现溢出,使用long long
        long long right = x/2+1;
        while(left <= right) {
            long long mid = (left+right)/2;
            if (mid*mid == x) {
                return mid;
            } else if (mid*mid < x) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return right;
    }
};

 

 




Sqrt(x)_LeetCode

原文:http://www.cnblogs.com/SYSU-Bango/p/7988980.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!