Skip to content

Commit 208cd92

Browse files
authored
Added task 693.
1 parent bc8918c commit 208cd92

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
}

0 commit comments

Comments
 (0)