Problem

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. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Example

Given num = 8 return true
Given num = 14 return false

Note

当num非0,用num除以2,3,5直到不能整除,最后余数为1就是ugly num。

Solution

1. Iteration

public class Solution {
    public boolean isUgly(int num) {
        int[] divs = {2, 3, 5};
        for (int div: divs) {
            while (num!= 0 && num % div == 0) {
                num /= div;
            }
        }
        return num == 1;
    }
}

2. Recursion

public class Solution {
    public boolean isUgly(int num) {
        if (num == 0) return false;
        if (num == 1) return true;
        if (num % 2 == 0) return isUgly(num/2);
        if (num % 3 == 0) return isUgly(num/3);
        if (num % 5 == 0) return isUgly(num/5);
        else return false;
    }
}

linspiration
161 声望53 粉丝