Preface explains

Algorithm learning, daily brush record.

Subject to connect

Number of ugly

The subject content

Give you an integer n, please determine whether n is ugly. If so, return true; Otherwise, return false.

Ugly numbers are positive integers that contain only prime factors 2, 3, and 5.

Example 1:

Enter n = 6

Output: true,

6 = 2 × 3

Example 2:

Enter: n = 8

Output: true,

8 = 2 × 2 × 2

Example 3:

Enter: n = 14

Output: false

Explanation: 14 is not ugly because it contains another prime factor, 7.

Example 4:

Enter n = 1

Output: true,

Explanation: 1 is usually considered an ugly number.

Tip:

-2^31 <= n <= 2^31 – 1

The analysis process

Cycle judgment: each cycle determines whether it can be divisible by 2 or 3 or 5. If it can be divisible, the value after being divisible is returned.

If there is a number that cannot be divisible by 2, 3 and 5, it is not ugly.

If it ends up being divisible to 1, it’s an ugly number.

To solve the code

Class Solution {public Boolean isUgly(int num) {if (num <= 0) {return false; } else if (num == 1) {return true; Int n = divide(num); int n = divide(num); If (n == -1) {// If (n == -1) {return false; } else if (n == 1) {return true; } // divide(n > 1) {// divide(n, 3, 5); If (n == -1) {// If (n == -1) {return false; } } return true; }} private int divide(int n) {if (n % 2 == 0) {return n / 2; } else if (n % 3 == 0) { return n / 3; } else if (n % 5 == 0) { return n / 5; } else { return -1; }}}Copy the code

Submit the results

It took 1ms to execute, beating 100.00% of the user in time, 35.5MB of memory consumption, and 48.98% of the user in space.

The original link

Original link: ugly number