What's the best way in JavaScript to test if a given parameter is a square number?

后端 未结 7 2640
忘了有多久
忘了有多久 2021-02-19 06:19

I created a function that will test to see if a given parameter is a square number.

Read about square numbers here: https://en.wikipedia.org/?title=Square_number

<
7条回答
  •  感情败类
    2021-02-19 07:15

    //1st 
    var isPerfectSquare = function(num) {
       return Math.sqrt(num) % 1 === 0;
    }
    
    //2nd: loop through all the number from 1 to num 
    var isPerfectSquare = function(num) {
        
        for(let i=1; i <= num ; i++){
            let d = i * i;
            if(d === num){
                return true
            }
        }
    }
    
    // Optimize solution: Binary Search 
    var isPerfectSquare = function(num) {
    
        if(num ==1)return true
        let left = 2;
        let right = Math.floor(num/2);
        while(left <= right){
            let middle = Math.floor((left + right)/2)
            let sqr = middle * middle;
            if(sqr == num){
                return true
            }else{
                if(sqr > num){
                  right = middle -1
                }else{
                    left = middle + 1
                }
            }  
        }
        
        return false
    };

提交回复
热议问题