solution in javascript - 13 lines of code


  • 0
    F

    We can first search for the range which contains the possible square root, then within that range, continue to check each number, if there is one, return true, otherwise, return false.
    For example: to find square root of 49. first divide 49 by 2 = 24, 24x24 > 49, divide 24 by 2 = 12, 12x12> 49, divide 12 by 2 = 6, 6x6 < 49
    we find the range 12~6, then find square root in this range, if there is, then we find it.

    var isPerfectSquare = function(num) {
        if(num === 1) return true;
        var div = parseInt(num/2), i;
        while(div*div > num) {
            div = parseInt(div/2);
        }
        for(i = div; i< div *2; i++) {
            if(i*i === num) {
                return true;
            }
        }
        return false;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.