|
| 1 | +def get_reverse_bit_string(bn : int) -> str: |
| 2 | + """ return the bit string of an interger |
| 3 | + """ |
| 4 | + bit_string = "" |
| 5 | + for trk in range(0, 32): |
| 6 | + bit_string += str(bn % 2) |
| 7 | + bn = bn >> 1 |
| 8 | + return bit_string |
| 9 | + |
| 10 | + |
| 11 | +def reverse_bit(n: int) -> str: |
| 12 | + """ |
| 13 | + Take in an 32 bit integer, reverse its bits, |
| 14 | + return a string of reverse bits |
| 15 | +
|
| 16 | + result of a reverse_bit and operation on the integer provided. |
| 17 | +
|
| 18 | + >>> reverse_bit(25) |
| 19 | + '00000000000000000000000000011001' |
| 20 | + >>> reverse_bit(37) |
| 21 | + '00000000000000000000000000100101' |
| 22 | + >>> reverse_bit(21) |
| 23 | + '00000000000000000000000000010101' |
| 24 | + >>> reverse_bit(58) |
| 25 | + '00000000000000000000000000111010' |
| 26 | + >>> reverse_bit(0) |
| 27 | + '00000000000000000000000000000000' |
| 28 | + >>> reverse_bit(256) |
| 29 | + '00000000000000000000000100000000' |
| 30 | + >>> reverse_bit(-1) |
| 31 | + Traceback (most recent call last): |
| 32 | + ... |
| 33 | + ValueError: the value of input must be positive |
| 34 | +
|
| 35 | + >>> reverse_bit(1.1) |
| 36 | + Traceback (most recent call last): |
| 37 | + ... |
| 38 | + TypeError: Input value must be a 'int' type |
| 39 | +
|
| 40 | + >>> reverse_bit("0") |
| 41 | + Traceback (most recent call last): |
| 42 | + ... |
| 43 | + TypeError: '<' not supported between instances of 'str' and 'int' |
| 44 | + """ |
| 45 | + if n < 0: |
| 46 | + raise ValueError("the value of input must be positive") |
| 47 | + elif isinstance(n, float): |
| 48 | + raise TypeError("Input value must be a 'int' type") |
| 49 | + elif isinstance(n, str): |
| 50 | + raise TypeError("'<' not supported between instances of 'str' and 'int'") |
| 51 | + ans = 0 |
| 52 | + # iterator over [1 to 32],since we are dealing with 32 bit integer |
| 53 | + for i in range(1, 33): |
| 54 | + # left shift the bits by unity |
| 55 | + ans = ans << 1 |
| 56 | + # get the end bit |
| 57 | + k = n % 2 |
| 58 | + # right shif the bits by unity |
| 59 | + n = n >> 1 |
| 60 | + # add that bit to our ans |
| 61 | + ans = ans | k |
| 62 | + return get_reverse_bit_string(ans) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + import doctest |
| 67 | + doctest.testmod() |
0 commit comments