-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-number-with-alternating-bits.cpp
More file actions
60 lines (45 loc) · 1.09 KB
/
Copy pathbinary-number-with-alternating-bits.cpp
File metadata and controls
60 lines (45 loc) · 1.09 KB
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
//question//
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
Constraints:
1 <= n <= 231 - 1
//solution//
class Solution {
public:
bool hasAlternatingBits(int n) {
string num = "";
while(n!=0)
{
int rem = n%2;
num = num + to_string(rem);
n = n/2;
}
if(num[0]==num[1])
{
return false;
}
for(int i=0;i<num.size();i++)
{
if((i%2==0 && num[i]==num[0]) || (i%2!=0 && num[i]==num[1]) )
{
continue;
}
else
{
return false;
}
}
return true;
}
};