My solution works everywhere but in leetcode, what can I do?


  • -1
    R
    /**
     * @param {number} num
     * @return {boolean}
     */
    var isUgly = function(num) {
        if(num === 1){
            return true;
        }
        
        num = removeMultiples(num, 2);
        num = removeMultiples(num, 3);
        num = removeMultiples(num, 5);
        
        if(num > 1){
            return false;
        } 
        
        return true;
    };
    
    function removeMultiples(n, base){
        while((n % base) === 0){
            n = n/base;
        }
        return n;
    }

  • 0
    W

    You're forgetting about when num = 0.


  • 0
    D

    I changed your code to make it work. Basically, just change the line if (num <= 0). You might wonder why it is num <=0? Because the statement says: "Ugly numbers are positive numbers...", so if it is non-positive, it is not a ugly number.

    /**
     * @param {number} num
     * @return {boolean}
     */
    var isUgly = function(num) {
        if(num <= 0){
            return false;
        }
    
        num = removeMultiples(num, 2);
        num = removeMultiples(num, 3);
        num = removeMultiples(num, 5);
    
        return num == 1;
    };
    
    function removeMultiples(n, base){
        while((n % base) === 0){
            n = n/base;
        }
        return n;
    }

Log in to reply
 

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