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

[LeetCode]69 Sqrt(x)

时间:2015-01-04 19:44:12      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/sqrtx/

http://blog.csdn.net/linhuanmars/article/details/20089131

public class Solution {
    public int sqrt(int x) {
        
        // Assume x >= 0
        if (x == 0)
            return 0;
        
        return s(x, 0L, (long)x);
    }
    
    private int calc(int x, long low, long high)
    {
        // Why using long.
        // is because we might calculate  (MAX_VALUE / 2 + somenumber) ^ 2
        
        if (low > high)
        {
            // This is the stop point.
            return (int)high;
        }
        
        long mid = (low + high) / 2;
        long y = mid * mid;
        if (x == y)
        {
            return (int)mid;
        }
        else if (x > y)
        {
            return calc(x, mid + 1, high);
        }
        else
        {
            return calc(x, low, mid - 1);
        }
    }
}


[LeetCode]69 Sqrt(x)

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1598893

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