Categories:

Tags:



Problem

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return true if n is an ugly number.

Constraints

  • -231 <= n <= 231 - 1

Solution

The problem Ugly Number can be solved by dividing positive integers with 2, 3 or 5 until it becomes indivisible and then checking if the result is 1 or not.

Implementation

class Solution
{
  public:
    bool isUgly(int n)
    {
        if (n <= 0)
            return false;

        while (n % 2 == 0)
            n /= 2;
        while (n % 3 == 0)
            n /= 3;
        while (n % 5 == 0)
            n /= 5;

        return n == 1;
    }
};