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

LeetCode--Sqrt(x)

时间:2015-01-12 17:41:51      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二分查找   牛顿迭代   

Implement int sqrt(int x).

Compute and return the square root of x.

二分查找法:

class Solution {
public:
    int sqrt(int x) 
    {
        int high = INT_MAX;
        int low = 0;
        while(low <=high)
        {
            long long mid = (low+high)/2;
            long long temp = mid*mid;
            if(temp == x)
                return mid;
            else if(temp < x)
                low = mid+1;
            else
                high = mid-1;
        }
        return high;
    }
};

牛顿迭代法待续

LeetCode--Sqrt(x)

标签:leetcode   二分查找   牛顿迭代   

原文地址:http://blog.csdn.net/shaya118/article/details/42644395

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