Write a program to check whether a given number is an ugly number.

    Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

    Example 1:

    1. Input: 6
    2. Output: true
    3. Explanation: 6 = 2 × 3

    Example 2:

    1. Input: 8
    2. Output: true
    3. Explanation: 8 = 2 × 2 × 2

    Example 3:

    1. Input: 14
    2. Output: false
    3. Explanation: 14 is not ugly since it includes another prime factor 7.

    Note:

    1. 1 is typically treated as an ugly number.
    2. Input is within the 32-bit signed integer range:263. Ugly Number (E) - 图1.

    题意

    判断一个数的因数是否只有2,3,5。

    思路

    除以所有的2,3,5,判断最后留下的数是不是1。


    代码实现

    1. class Solution {
    2. public boolean isUgly(int num) {
    3. // 特殊情况排除
    4. if (num == 0) {
    5. return false;
    6. }
    7. while (num % 2 == 0) {
    8. num /= 2;
    9. }
    10. while (num % 3 == 0) {
    11. num /= 3;
    12. }
    13. while (num % 5 == 0) {
    14. num /= 5;
    15. }
    16. return num == 1;
    17. }
    18. }