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

Jan 19 - Sqrt(x); Math; Binary Search;

时间:2016-01-20 13:09:06      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

We should keep in mind that never let the integer value overranged or overstacked..

Here is the trick, instead of comparing the square of a interger with the target value, we can compare the integer value i with the quotient x/i;

if(i > x/i) high = i - 1; if(i < x/i) low = i +1, the condition of the while is loop is low < high. Thus when the loop ends, low = high. There are two results, one is the low point to the integer which is the sqrt(x), the other is low = sqrt(x)+1. We need to check the two cases in the end.

Code:

public class Solution {
    public int mySqrt(int x) {
        if(x<0) return -1;
        if(x == 0) return 0;
        if(x == 1) return 1;
        int low = 1, high = x;
        while(low < high){
            int mid = low+(high-low)/2;
            int quotient = x/mid;
            if(quotient == mid) return mid;
            else if(mid > quotient){
                high = mid-1;
            }
            else{
                low = mid + 1;
            }
        }
        int quotient = x/low;
        if(low > quotient) return low -1;
        return low;
    }
}

  

Newton‘s method to get square root:

Code:

public int mySqrt(int x) {
    if (x == 0) return 0;
    long i = x;
    while(i > x / i)  
        i = (i + x / i) / 2;            
    return (int)i;
}

 

Jan 19 - Sqrt(x); Math; Binary Search;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5144697.html

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