• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

LeetCode – Easy – 693. Binary Number with Alternating Bits

2周前 (04-07) 8次浏览

Topic

• Bit manipulation

Description

https://leetcode.com/problems/binary-number-with-alternating-bits/

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.
``````

Example 4:

``````Input: n = 10
Output: true
Explanation: The binary representation of 10 is: 1010.
``````

Example 5:

``````Input: n = 3
Output: false
``````

Constraints:

• \$1 <= n <= 2^{31} – 1\$

Submission

``````public class BinaryNumberWithAlternatingBits {

// 方法一：我写的
public boolean hasAlternatingBits(int n) {
int first = n & 1, second;
n >>= 1;
while (n != 0) {
second = n & 1;
if (first == second)
return false;
first = second;
n >>= 1;
}
return true;
}

// 方法二：别人写
public boolean hasAlternatingBits2(int n) {
n = n ^ (n >> 1);
return (n & n + 1) == 0;
}

}
``````

Test

``````import static org.junit.Assert.*;
import org.junit.Test;

public class BinaryNumberWithAlternatingBitsTest {

@Test
public void test() {
BinaryNumberWithAlternatingBits obj = new BinaryNumberWithAlternatingBits();

assertTrue(obj.hasAlternatingBits(5));
assertFalse(obj.hasAlternatingBits(7));
assertFalse(obj.hasAlternatingBits(11));
assertTrue(obj.hasAlternatingBits(10));
assertFalse(obj.hasAlternatingBits(3));

assertTrue(obj.hasAlternatingBits2(5));
assertFalse(obj.hasAlternatingBits2(7));
assertFalse(obj.hasAlternatingBits2(11));
assertTrue(obj.hasAlternatingBits2(10));
assertFalse(obj.hasAlternatingBits2(3));
}
}
``````

javajunitbce

0

0 收藏

QQ

作者的其它热门文章

【清华大学】《逻辑学概论》笔记
《Java8实战》笔记（10）：用Optional取代null
Kafka学习笔记
Redis学习笔记