码迷,mamicode.com
首页 > 其他好文 > 详细

Sqrt(x)_LeetCode

时间:2017-12-05 20:07:02      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:guarantee   利用   强制   inpu   ant   roo   double   imp   调用   

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

标签:guarantee   利用   强制   inpu   ant   roo   double   imp   调用   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!