File tree Expand file tree Collapse file tree
LeetCode/0693-binary-number-with-alternating-bits Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 >  ; </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 >  ; </p >
27+ <p ><strong >Constraints:</strong ></p >
28+
29+ <ul >
30+ <li><code>1 <= n <= 2<sup>31</sup> - 1</code></li>
31+ </ul >
Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments