File tree Expand file tree Collapse file tree 3 files changed +74
-0
lines changed
main/java/g0601_0700/s0693_binary_number_with_alternating_bits
test/java/g0601_0700/s0693_binary_number_with_alternating_bits Expand file tree Collapse file tree 3 files changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ package g0601_0700 .s0693_binary_number_with_alternating_bits ;
2+
3+ // #Easy #Bit_Manipulation
4+
5+ public class Solution {
6+ public boolean hasAlternatingBits (int n ) {
7+ int prev = -1 ;
8+ while (n != 0 ) {
9+ int v = n & 1 ;
10+ n = n >> 1 ;
11+ if (prev == v ) {
12+ return false ;
13+ }
14+ prev = v ;
15+ }
16+ return true ;
17+ }
18+ }
Original file line number Diff line number Diff line change 1+ 693\. Binary Number with Alternating Bits
2+
3+ Easy
4+
5+ Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
6+
7+ ** Example 1:**
8+
9+ ** Input:** n = 5
10+
11+ ** Output:** true
12+
13+ ** Explanation:** The binary representation of 5 is: 101
14+
15+ ** Example 2:**
16+
17+ ** Input:** n = 7
18+
19+ ** Output:** false
20+
21+ ** Explanation:** The binary representation of 7 is: 111.
22+
23+ ** Example 3:**
24+
25+ ** Input:** n = 11
26+
27+ ** Output:** false
28+
29+ ** Explanation:** The binary representation of 11 is: 1011.
30+
31+ ** Constraints:**
32+
33+ * <code >1 <= n <= 2<sup >31</sup > - 1</code >
Original file line number Diff line number Diff line change 1+ package g0601_0700 .s0693_binary_number_with_alternating_bits ;
2+
3+ import static org .hamcrest .CoreMatchers .equalTo ;
4+ import static org .hamcrest .MatcherAssert .assertThat ;
5+
6+ import org .junit .jupiter .api .Test ;
7+
8+ class SolutionTest {
9+ @ Test
10+ void hasAlternatingBits () {
11+ assertThat (new Solution ().hasAlternatingBits (5 ), equalTo (true ));
12+ }
13+
14+ @ Test
15+ void hasAlternatingBits2 () {
16+ assertThat (new Solution ().hasAlternatingBits (7 ), equalTo (false ));
17+ }
18+
19+ @ Test
20+ void hasAlternatingBits3 () {
21+ assertThat (new Solution ().hasAlternatingBits (11 ), equalTo (false ));
22+ }
23+ }
You can’t perform that action at this time.
0 commit comments