LeetCode - Easy - 693. Binary Number with Alternating Bits

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 1 <= n <= 2^{31} - 1 1<=n<=2311

Analysis

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

方法二:别人写的。link

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));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值