Problem: Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Write a method to check whether a given number is an ugly number.
Example:
Input: 10 Output: true Explanation: 10 = 2 × 5
Approach: Nothing to explain. Just look at the code.
Implementation in C#:
public bool IsUgly(int num)
{
if (num == 0)
{
return false;
}
while (num != 1)
{
if (num % 2 == 0)
{
num /= 2;
}
else if (num % 3 == 0)
{
num /= 3;
}
else if (num % 5 == 0)
{
num /= 5;
}
else
{
return false;
}
}
return true;
}
Complexity: O(logn)
No comments:
Post a Comment