reverse_bits
1# @leet start 2class Solution: 3 def reverseBits(self, n: int) -> int: 4 """ 5 We can find the bits of an integer by checking each bit and anding it with 6 1 to see if it is set. 7 Then for each bit in the output, we set it by bitwise ORing it in the location 8 it needs to go. 9 10 This solution goes bit by bit, but an optimized solution might go byte 11 by byte and using shifting with a mask, but that's more complicated. 12 """ 13 res = 0 14 for i in range(32): 15 bit = (n >> i) & 1 16 res |= bit << 31 - i 17 return res 18 19 20# @leet end 21q = Solution().reverseBits 22 23 24def test(): 25 assert q(4294967293) == 3221225471
class
Solution:
3class Solution: 4 def reverseBits(self, n: int) -> int: 5 """ 6 We can find the bits of an integer by checking each bit and anding it with 7 1 to see if it is set. 8 Then for each bit in the output, we set it by bitwise ORing it in the location 9 it needs to go. 10 11 This solution goes bit by bit, but an optimized solution might go byte 12 by byte and using shifting with a mask, but that's more complicated. 13 """ 14 res = 0 15 for i in range(32): 16 bit = (n >> i) & 1 17 res |= bit << 31 - i 18 return res
def
reverseBits(self, n: int) -> int:
4 def reverseBits(self, n: int) -> int: 5 """ 6 We can find the bits of an integer by checking each bit and anding it with 7 1 to see if it is set. 8 Then for each bit in the output, we set it by bitwise ORing it in the location 9 it needs to go. 10 11 This solution goes bit by bit, but an optimized solution might go byte 12 by byte and using shifting with a mask, but that's more complicated. 13 """ 14 res = 0 15 for i in range(32): 16 bit = (n >> i) & 1 17 res |= bit << 31 - i 18 return res
We can find the bits of an integer by checking each bit and anding it with 1 to see if it is set. Then for each bit in the output, we set it by bitwise ORing it in the location it needs to go.
This solution goes bit by bit, but an optimized solution might go byte by byte and using shifting with a mask, but that's more complicated.
def
q(n: int) -> int:
4 def reverseBits(self, n: int) -> int: 5 """ 6 We can find the bits of an integer by checking each bit and anding it with 7 1 to see if it is set. 8 Then for each bit in the output, we set it by bitwise ORing it in the location 9 it needs to go. 10 11 This solution goes bit by bit, but an optimized solution might go byte 12 by byte and using shifting with a mask, but that's more complicated. 13 """ 14 res = 0 15 for i in range(32): 16 bit = (n >> i) & 1 17 res |= bit << 31 - i 18 return res
We can find the bits of an integer by checking each bit and anding it with 1 to see if it is set. Then for each bit in the output, we set it by bitwise ORing it in the location it needs to go.
This solution goes bit by bit, but an optimized solution might go byte by byte and using shifting with a mask, but that's more complicated.
def
test():