leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit ef565e321f29ebb749d8fdad74a0f7d7105ddee0
parent 534ded84da3cbdf9c51b3f65dedde4321541a376
Author: Jack Sangdahl <jack@pngu.org>
Date:   Tue, 17 Feb 2026 20:05:02 -0700

693. binary number with alternating bits

Diffstat:
Mbinary_num_alter_bits.c | 18+++++++++++++-----
Mbinary_num_alter_bits.py | 4++--
2 files changed, 15 insertions(+), 7 deletions(-)

diff --git a/binary_num_alter_bits.c b/binary_num_alter_bits.c @@ -1,5 +1,7 @@ // 693. Binary Number with Alternating Bits #include "leetcode.h" +#include <cassert> +#include <stdio.h> /* * given a positive integer, check whether it has alternating bits: namely if @@ -7,12 +9,18 @@ */ bool hasAlternatingBits(int n) { - long long int x = n ^ (n >> 1); - return !(x & (x + 1)); + n ^= (n >> 1); + return !(n & n + 1); } int main() { - printf("%d\n", hasAlternatingBits(5)); // expect: 1 - printf("%d\n", hasAlternatingBits(7)); // expect: 0 - printf("%d\n", hasAlternatingBits(11)); // expect: 0 + bool r1 = hasAlternatingBits(5); + bool r2 = hasAlternatingBits(7); + bool r3 = hasAlternatingBits(11); + printf("%d\n", r1); // expect: 1 + assert(r1 == true); + printf("%d\n", r2); // expect: 0 + assert(r2 == false); + printf("%d\n", r3); // expect: 0 + assert(r3 == true); } diff --git a/binary_num_alter_bits.py b/binary_num_alter_bits.py @@ -12,8 +12,8 @@ class Solution(object): :type n: int :rtype: bool """ - x = n ^ (n >> 1) - return (x & (x + 1)) == 0 + n ^= n >> 1 + return (n & n + 1) == 0 if __name__ == "__main__":