263. Ugly number

Difficulty: easy

Write a program to determine whether a given number is ugly.

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

Example 1:

Input: 6 Output: true Description: 6 = 2 x 3Copy the code

Example 2:

Input: 8 Output: true Description: 8 = 2 x 2 x 2Copy the code

Example 3:

Input: 14 Output: false Explanation: 14 is not ugly because it contains another prime factor, 7.Copy the code

Description:

  1. 1Is ugly.
  2. The input cannot exceed the range of 32-bit signed integers: [−231, 231 − 1].

Solution

It’s a little bit more complicated

Language: golang

func isUgly(num int) bool { if num == 0 { return false } if num == 1 { return true } for { if num ! If num%2! = 1 {// if num%2! If num%3! = 0 {// if num%3! If num%5! = 0 {// if num%5! = 0 { return false } else { num = num / 5 } } else { num = num / 3 } } else { num = num / 2 } } else { return true } } }Copy the code

Let’s look at an easier way

func isUgly(num int) bool { if num < 1 { return false } for { if num%2 == 0 { num /= 2 } else if num%3 == 0 { num /= 3 }  else if num%5 == 0 { num /= 5 } else if num == 1 { return true } else { return false } } }Copy the code