-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path263. Ugly Number.cpp
44 lines (33 loc) · 920 Bytes
/
263. Ugly Number.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// -----Approach 1: ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/ugly-number/
Time: 0 ms (Beats 100%), Space: 6 MB (Beats 55.61%)
*/
class Solution {
public:
bool isUgly(int n) {
if (n <= 0) return false;
while(n>1){
if (n % 2 == 0) n /=2;
else if (n % 3 == 0) n /=3;
else if (n % 5 == 0) n /=5;
else break;
}
return n == 1;
}
};
// -----Approach 2: ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/ugly-number/
Time: 0 ms (Beats 100%), Space: 6 MB (Beats 6.19%%)
*/
class Solution {
public:
bool isUgly(int n) {
if (n <= 0) return false;
for (int i=2; i<6 && n; i++)
while ( n%i == 0 )
n /= i;
return n == 1;
}
};