Share my simple Java solution


  • 11
    N

    Continually divide the number by 2,3,5. If it's ugly, the result must be 1.

    public class Solution {
        public boolean isUgly(int num) {
            if(num <= 0) return false;
            while((num % 2) == 0) num /= 2;
            while((num % 3) == 0) num /= 3;
            while((num % 5) == 0) num /= 5;
            return num == 1;
        }
    }
    

    Thanks to braydenCN's advice. Revised some code.


  • 0
    B

    why not just return num == 1;


  • 0
    N

    You are right. That would be more concise.


  • 0

    ugly number = 1 * 2^x * 3^y * 5^z, x,y,z can be any integer >= 0.


  • 0
    L

    @Neo_Zhang

    Great minds think alike. Here is mine. I put 5 in the first so it can divide faster.
    public boolean isUgly(int num) {
    if(num <= 0) return false;
    while(num % 5 == 0){
    num /= 5;
    }
    while(num % 3 == 0){
    num /= 3;
    }

        while(num % 2 == 0){
            num >>=1 ;
        }
        
        return num == 1;
        
    }

Log in to reply
 

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