# My 2ms java solution

• ``````public boolean isUgly(int num) {
if(num==1) return true;
if(num==0) return false;
while(num%2==0) num=num>>1;
while(num%3==0) num=num/3;
while(num%5==0) num=num/5;
return num==1;
}``````

• no bother "num=num>>1", optimization is done by compiler. just write num = num / 2 to make it (a little) clear and consistent

1. It is not necessary to judge whether num equals to 1
2. num%2 == 0 can be written as num & 1 == 0, which is faster

1. agreed 2) that sounds premature and it's better to be readable than tricky if production code (which this is not :)

• i dont think so

• @fpwang said in My 2ms java solution:

done

Is this applied for all versions JAVA compliers?

• @mirocody yes it's appied to all (currently in wide use): none of them actually do it. That is, at .java → .class compilation time (javac), however JIT may do it if necessary on the target platform.

• @TWiStErRob said in My 2ms java solution:

JIT

Thank you for the response! That does make sense to me!

• Bit operation does not make code faster in this question.

• @kittyfeng What is the running time for this solution?

• @acheiver the worst input it can receive is a large number composed of prime factors `2`, `3`, `5`, because that makes the while loops continue for a while. The worst of all these is in the form of `n = p^k`. To work through that, it'll need `log_p(n) = k` steps. The slowest decrease will happen when the input is using the factor `2`. So in general the algorithm is `O(log_2(n))`.

BUT, because the input size is constrained to Java's `int` (as opposed to `BigInteger`), the worst number is `2^30`, so for any possible input in Java, it'll take less than roughly 30 steps to find a result, which means that this runs in constant time: `O(1)`.

• @kittyfeng you don't need to junge whether `num==1 or 0`as you write `if(num==1) return true; f(num==0) return false;` because if `num==1` the result is true,and num is positive number In description.

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