leetcode

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

commit 7d9f4fd9a9e5b846a9fe7e3ff6c794722d045eb6
parent 91183f92ac13aa4ca9cc6d18629483aa9762b54e
Author: Jack Sangdahl <jack@pngu.org>
Date:   Mon,  3 Nov 2025 17:47:09 -0700

693. binary number with alternating bits

Diffstat:
Abinary_num_alter_bits.c | 18++++++++++++++++++
Abinary_num_alter_bits.py | 23+++++++++++++++++++++++
2 files changed, 41 insertions(+), 0 deletions(-)

diff --git a/binary_num_alter_bits.c b/binary_num_alter_bits.c @@ -0,0 +1,18 @@ +// 693. Binary Number with Alternating Bits +#include "leetcode.h" + +/* + * given a positive integer, check whether it has alternating bits: namely if + * two adjacent bits will always have different values + */ + +bool hasAlternatingBits(int n) { + long long int x = n ^ (n >> 1); + return !(x & (x + 1)); +} + +int main() { + printf("%d\n", hasAlternatingBits(5)); // expect: 1 + printf("%d\n", hasAlternatingBits(7)); // expect: 0 + printf("%d\n", hasAlternatingBits(11)); // expect: 0 +} diff --git a/binary_num_alter_bits.py b/binary_num_alter_bits.py @@ -0,0 +1,23 @@ +# 693. 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 +""" + + +class Solution(object): + def hasAlternatingBits(self, n): + """ + :type n: int + :rtype: bool + """ + x = n ^ (n >> 1) + return (x & (x + 1)) == 0 + + +if __name__ == "__main__": + obj = Solution() + print(obj.hasAlternatingBits(5)) + print(obj.hasAlternatingBits(7)) + print(obj.hasAlternatingBits(11))