↓Skip to main content
  1. LeetCode/

LeetCode 693: Binary Number with Alternating Bits

·1 min· ·
LeetCode Easy Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-30

  • Submissions: Wrong Answer → Accepted ×4

Approach
#

With strings: bin(n) must contain neither "00" nor "11". With bits (Bit Manipulation): alternating bits make every bit of x = n ^ (n >> 1) a 1, and x & (x + 1) == 0 checks that it is all ones.

My Attempts
#

Attempt 1 wrote '00' in s or '11' in s, the exact opposite: 2 (10) returned False. not in ... and not in passed.

Solution
#

class Solution:
    def hasAlternatingBits(self, n: int) -> bool:
        x = n ^ (n >> 1)
        return x & (x + 1) == 0

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • The condition is no 00 and no 11; do not invert it.

Interview Explanation
#

With alternating bits, n XOR (n » 1) is all ones, which I verify with x & (x + 1) == 0. Time O(1).

Related

LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 476: Number Complement
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 476 note: build an all-ones mask as long as num; num ^ mask is the complement
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive