-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bleak Numbers.cpp
95 lines (83 loc) · 1.52 KB
/
Bleak Numbers.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*------------- ALL POSSIBLE APPROACHES -----------------*/
/*----------APPROACH - 1 (TLE)----------*/
class Solution
{
public:
int is_bleak(int n)
{
for(int i=1;i<=n;i++)
{
if(i+__builtin_popcount(i)==n)
return 0;
}
return 1;
}
};
/*-----------APPROACH - 2 (TLE)------------*/
class Solution
{
public:
int countSetBits(int num)
{
bitset<32> bits(num); // Assuming a 32-bit integer
return bits.count();
}
int is_bleak(int n)
{
for(int i=1;i<=n;i++)
{
if(i+countSetBits(i)==n)
return 0;
}
return 1;
}
};
/*-------------APPROACH -3 -----------------*/
class Solution
{
public:
int is_bleak(int n)
{
for (int i = n - 1; i >= n - ceil(log2(n)); i--)
{
if (i + __builtin_popcount(i) == n)
return 0;
}
return 1;
}
};
/*---------------APPROACH - 4 -------------------*/
class Solution
{
public:
int countSetBits(int x)
{
int count = 0;
while (x)
{
x &= (x - 1);
count++;
}
return count;
}
int ceilLog(int x)
{
int count = 0;
x--;
while (x > 0)
{
x = x >> 1;
count++;
}
return count;
}
int is_bleak(int n)
{
for (int x = n-ceilLog(n); x < n; x++)
{
if (x + countSetBits(x) == n)
return 0;
}
return 1;
}
};