Post

Ugly Number

1. Problem Statement

2. Algorithm Design and Approach

  • greedy
  • Using While Loop to check prime number in n

3. Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

class Solution
{
public:
    bool isUgly(int n)
    {
        while ((n % 5) == 0 && (n >= 5))
        {
            n /= 5;
        }
        while ((n % 3) == 0 && (n >= 3))
        {
            n /= 3;
        }
        while ((n % 2) == 0 && (n >= 2))
        {
            n /= 2;
        }
        if (n != 1)
        {
            return false;
        }
        return true;
    }
};

4. Example Walkthrough

n = 6

  • true

n = 1

  • false

n = 14

  • false

5. Conclusion

  • ”%=” Operator changes value of origin left value
  • Using “If” and “&&” Operator is not good for minimize time complexity.
This post is licensed under CC BY 4.0 by the author.