Java recursive solution 2ms(with explanation)

  • 0

    From the easy understand point of view, I think using reclusive is more nature in this problem.

    Basically an ugly number can be divided by 2, 3 or 5, and after divided, the rest number should be also possible divided by 2, 3 or 5, then repeat until we can get 1 in the final round, so it's a very nature recursive thinking.

    public class Solution {
        public boolean isUgly(int num) {
            if(num <= 0) return false;
            return re(num);
        private boolean re(int num){
            if(num == 1) return true;
    //the num%N part can exclude those number which can't be divided by N, and prevent them into recursive method.
            return ((num%2 == 0) &&re(num/2)) || ((num%3 == 0) &&re(num/3)) || ((num%5 == 0) &&re(num/5));

Log in to reply

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