Iam_Sandeep

Range bitwise and

Jun 13th, 2022 (edited)
723
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.63 KB | None | 0 0
  1. class Solution:
  2.     def rangeBitwiseAnd(self, left: int, right: int) -> int:
  3.         steps=0
  4.         while left!=right:
  5.             steps+=1
  6.             left=left>>1
  7.             right=right>>1
  8.         return left<<steps
  9. ```
  10. The idea is very simple:
  11.  
  12. 1.last bit of (odd number & even number) is 0.
  13. 2.when m != n, There is at least an odd number and an even number, so the last bit position result is 0.
  14. 3.Move m and n rigth a position.
  15. Keep doing step 1,2,3 until m equal to n, use a factor to record the iteration time.
  16. return left<<steps because left reaches to 0 early then right while doing right shift operations
  17.  
  18.  
  19. ```
Add Comment
Please, Sign In to add comment