From a3bb227bb88db7d6fd01b30c681f3f43a2075e4a Mon Sep 17 00:00:00 2001 From: Arjit Arora <42044030+arjitarora26@users.noreply.github.com> Date: Mon, 24 Oct 2022 11:27:09 +0530 Subject: [PATCH 1/2] Add function for highest set bit location --- bit_manipulation/highest_set_bit.py | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 bit_manipulation/highest_set_bit.py diff --git a/bit_manipulation/highest_set_bit.py b/bit_manipulation/highest_set_bit.py new file mode 100644 index 000000000000..8a5f3953e251 --- /dev/null +++ b/bit_manipulation/highest_set_bit.py @@ -0,0 +1,34 @@ +def get_highest_set_bit_position(number: int) -> int: + """ + Returns position of the highest set bit of a number. + Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious + >>> get_highest_set_bit_position(25) + 5 + >>> get_highest_set_bit_position(37) + 6 + >>> get_highest_set_bit_position(1) + 1 + >>> get_highest_set_bit_position(4) + 3 + >>> get_highest_set_bit_position(0.8) + Traceback (most recent call last): + ... + TypeError: Input value must be an 'int' type + """ + if not isinstance(number, int): + raise TypeError("Input value must be an 'int' type") + + position = 0 + while number: + position += 1 + number >>= 1 + if number == 0: + break + + return position + + +if __name__ == "__main__": + import doctest + + doctest.testmod() From d3047c05064972c7b6e906a9319fdf06b48845c9 Mon Sep 17 00:00:00 2001 From: Arjit Arora <42044030+arjitarora26@users.noreply.github.com> Date: Thu, 27 Oct 2022 01:14:13 +0530 Subject: [PATCH 2/2] Address review comments --- bit_manipulation/highest_set_bit.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bit_manipulation/highest_set_bit.py b/bit_manipulation/highest_set_bit.py index 8a5f3953e251..21d92dcb9492 100644 --- a/bit_manipulation/highest_set_bit.py +++ b/bit_manipulation/highest_set_bit.py @@ -10,6 +10,8 @@ def get_highest_set_bit_position(number: int) -> int: 1 >>> get_highest_set_bit_position(4) 3 + >>> get_highest_set_bit_position(0) + 0 >>> get_highest_set_bit_position(0.8) Traceback (most recent call last): ... @@ -22,8 +24,6 @@ def get_highest_set_bit_position(number: int) -> int: while number: position += 1 number >>= 1 - if number == 0: - break return position