Skip to content

Commit 800bc47

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 7.6 MB (99.82%)
1 parent 7c639f5 commit 800bc47

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<p>Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> n = 5
8+
<strong>Output:</strong> true
9+
<strong>Explanation:</strong> The binary representation of 5 is: 101
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> n = 7
16+
<strong>Output:</strong> false
17+
<strong>Explanation:</strong> The binary representation of 7 is: 111.</pre>
18+
19+
<p><strong class="example">Example 3:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> n = 11
23+
<strong>Output:</strong> false
24+
<strong>Explanation:</strong> The binary representation of 11 is: 1011.</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
31+
</ul>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution {
2+
public:
3+
bool hasAlternatingBits(int n) {
4+
while (n) if ((n & 1) == ((n >>= 1) & 1)) return false;
5+
return true;
6+
}
7+
};

0 commit comments

Comments
 (0)