Ugly Number

  • Easy
  • keyword: Pattern, Number
  • 类似: Happy Number, Count Digit, Add Digits, Next/Prev Permutation
  • Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
  • Note that 1 is typically treated as an ugly number.

idea

  • 有规律吗, 并没有找到有直接的公式/算法可以解决.
  • 所以使用暴力解法.
  • 代码如下:
  public boolean isUgly(int num) {
    int[] factors = new int[]{2,3,5};
    if (num > 0) {
      for (int f : factors) {
        while (num % f == 0) {
          num /= f;
        }
      }
    }
    return num == 1;
  }