Home | Projects | Notes > Problem Solving > LC - E - 263. Ugly Number
This solution uses recursion.
Complexity Analysis:
Solution:
xxxxxxxxxx
121class Solution {
2public:
3 bool isUgly(int n) {
4 if (n <= 0) return false;
5
6 while (n % 2 == 0) n /= 2;
7 while (n % 3 == 0) n /= 3;
8 while (n % 5 == 0) n /= 5;
9
10 return n == 1;
11 }
12};
This solution uses recursion.
Complexity Analysis:
Solution:
xxxxxxxxxx
111class Solution {
2public:
3 bool isUgly(int n) {
4 if (n <= 0) return false;
5 if (n < 7) return true;
6 if (n % 2 == 0) return isUgly(n/2);
7 if (n % 3 == 0) return isUgly(n/3);
8 if (n % 5 == 0) return isUgly(n/5);
9 return false;
10 }
11};