Advertisement
693. Binary Number with Alternating Bits
EasyView on LeetCode
693.cs
C#
public class Solution
{
public bool HasAlternatingBits(int n)
{
// n = 0b010101
// n >> 2 = 0b000101
// n ^ (n >> 2) = 0b010000 = a
// a - 1 = 0b001111
// a & (a - 1) = 0
int a = n ^ (n >> 2);
return (a & (a - 1)) == 0;
}
}Advertisement