美文网首页
Square Root by binary search

Square Root by binary search

作者: Star_C | 来源:发表于2018-03-15 19:15 被阅读0次

    Question

    from lintcode
    Find the square root of a number(integer).

    Idea

    Start from 0 to the given number. Perform a binary search to find a number whose square is closest but no larger than the given number.

    public class Solution {
        /**
         * @param x: An integer
         * @return: The sqrt of x
         */
        public int sqrt(int x) {
            
            if (x == 0) return x;
            
            long start = 1;
            long end = x;
            while (start + 1 < end) {
                long mid = start + (end - start) / 2;
                if (mid * mid > x) {
                    end = mid;
                } else {
                    start = mid;
                }
            }
            if (start * start <= x)
              return (int)start;
            return (int)end;
        }
    }
    

    相关文章

      网友评论

          本文标题:Square Root by binary search

          本文链接:https://www.haomeiwen.com/subject/botkqftx.html