LeetCode -- Ugly Number
題目描述:
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
判斷一個數是否為ugly number。
對2,3,5執行以下過程:
不斷除n,直到無法整除。
最後剩余數字為1,則該數為ugly number。
實現代碼:
public class Solution {
public bool IsUgly(int num)
{
if(num <= 0){
return false;
}
num = Divide(num,2);
num = Divide(num,3);
num = Divide(num,5);
return num == 1;
}
private int Divide(int num, int a)
{
while(num % a == 0){
num /= a;
}
return num;
}
}