Created
April 19, 2015 16:05
-
-
Save philangist/4baae0043219f4f0add8 to your computer and use it in GitHub Desktop.
Bitwise AND of Numbers Range - Solution to https://leetcode.com/problems/bitwise-and-of-numbers-range/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def integer_to_bit_string(integer): | |
return bin(integer)[2:] | |
def pad_bit_strings(bit_string_1, bit_string_2): | |
difference = len(bit_string_1) - len(bit_string_2) | |
if difference < 0: | |
bit_string_1 = '0' * abs(difference) + bit_string_1 | |
else: | |
bit_string_2 = '0' * abs(difference) + bit_string_2 | |
return (bit_string_1, bit_string_2) | |
def bitwise_and(bit_string_1, bit_string_2): | |
bit_string = '' | |
for (i, bit_1) in enumerate(bit_string_1): | |
bit_2 = bit_string_2[i] | |
bit_string += str(int(bit_1) & int(bit_2)) | |
return bit_string | |
def range_bitwise_and(*args): | |
bit_strings = map(integer_to_bit_string, args) | |
bit_string = reduce(bitwise_and, bit_strings) | |
return int(bit_string, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment