My clean Java solution with explanation

  • -3

    We use another method private boolean isUgly(int num, int n) to handle 2, 3, 5 without produce duplicate codes.

    Use num == 0 and num == 1 to deal with end condition.

    The remaining logic is clean.


    public class Solution {
        public boolean isUgly(int num) {
            if (num == 0) { return false; }
            if (num == 1) { return true; }
            return isUgly(num, 2) || isUgly(num, 3) || isUgly(num, 5);
        private boolean isUgly(int num, int n) {
            return num % n == 0 ? isUgly(num / n) : false;

  • 0

    Can be quite slow, try for example num = -1458000000. That case alone takes about 1000 ms on the OJ (it's not among the test cases, I submitted your solution with a wrapper to test this). Or num = 2041200000, which takes about 300 ms. (I'm not the downvoter, though)

  • 0

    :) Of course it is slow. The tradeoff is that this solution is extensible for any "UGLY NUMBERS".

    Wanna fast? Use C pointer to pass number and reassign values.

    Actually I think the series of Ugly Numbers is totally meaningless. I don't know who invent the ugly numbers.

    But I would not join the company if they asked me this question in interview.

  • 0

    I don't know what "Use C pointer to pass number and reassign values" means, but does that make it 100000~1400000 times faster? That's how much faster my "normal" Java solution solves those cases.

    I don't see what you mean with extensible, either. How are other solutions not extensible?

  • 0

    100000~1400000 times faster?

    Did you mean your solution can solve input 2041200000 in 300ms/100000=0.003ms ?

  • 0

    Actually in around 0.0014ms, so even about 200000 times faster. Don't know why I wrote 100000, either a typo or I got confused by all the numbers. I still have "300000000/1400 = 214285.714" in the calculator...

Log in to reply

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