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.
Analyse: Continuously divide the number by 2, 3, 5. If the remaining number is one, then it's a ugly number.
Runtime: 4ms.
1 class Solution { 2 public: 3 bool isUgly(int num) { 4 if(num == 0) return false; 5 if(num == 1) return true; 6 7 while(num % 2 == 0) num /= 2; 8 while(num % 3 == 0) num /= 3; 9 while(num % 5 == 0) num /= 5; 10 11 if(num == 1) return true; 12 return false; 13 } 14 };
Runtime: 8ms.
1 class Solution { 2 public: 3 bool isUgly(int num) { 4 if(num == 0) return false; 5 if(num == 1) return true; 6 7 int arr[] = {2, 3, 5}; 8 int index = 0; 9 while(index < 3){ 10 while(num % arr[index] == 0) num /= arr[index]; 11 index++; 12 } 13 14 if(num == 1) return true; 15 return false; 16 } 17 };