My JavaScript solution, any better solution?


  • 0
    K

    My JavaScript solution:

    var isUgly = function (num) {
      if (num === 1) {
        return true;
      }
      if (num <= 0) {
        return false;
      }
      var mod2 = num % 2;
      var mod3 = num % 3;
      var mod5 = num % 5;
      if (mod2 && mod3 && mod5) {
        return false;
      } else if (!mod2) {
        return isUgly(num / 2);
      } else if (!mod3) {
        return isUgly(num / 3);
      } else if (!mod5) {
        return isUgly(num / 5);
      }
    }

  • 0
    W

    Here's mine, it ran in 188ms. It is probably slightly faster than yours because I do not declare the three mod variables that you do. I'm brand new to javascript but I think there is some time overhead with declaring variables. Also, you probably have a bit of memory overhead with the recursive function.

     var isUgly = function(num) {
    	if(num <= 0)
    		return false;
    	else if(num == 1)
    		return true;
    	while(num > 5)
    	{
    		if(num % 5 === 0) num = num / 5;
    		else if (num % 3 === 0) num = num / 3;
    		else if (num % 2 === 0) num = num / 2;
    		else return false;
    	}
    	return true;
        
    };

Log in to reply
 

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