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

LeetCode – Easy – 693. Binary Number with Alternating Bits

互联网 diligentman 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$

Analysis

方法一:我写的。思路就是将数转换成二进制形式,检测两两相邻数位是否相同,若有相同,则返回false,没有的,则返回true。

方法二:别人写的。link

LeetCode - Easy - 693. Binary Number with Alternating Bits

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学习笔记


程序员灯塔
转载请注明原文链接:LeetCode – Easy – 693. Binary Number with Alternating Bits
喜欢 (0)