LeetCode Solutions

263. Ugly Number

Time: $O(\log n)$

Space: $O(1)$

			

class Solution {
 public:
  bool isUgly(int n) {
    if (n == 0)
      return false;

    for (const int prime : {2, 3, 5})
      while (n % prime == 0)
        n /= prime;

    return n == 1;
  }
};
			

class Solution {
  public boolean isUgly(int n) {
    if (n == 0)
      return false;

    for (final int prime : new int[] {2, 3, 5})
      while (n % prime == 0)
        n /= prime;

    return n == 1;
  }
}
			

class Solution:
  def isUgly(self, n: int) -> bool:
    if n == 0:
      return False

    for prime in 2, 3, 5:
      while n % prime == 0:
        n //= prime

    return n == 1