201.bitwise-and-of-numbers-range.go 314 B

1234567891011121314
  1. import (
  2. "fmt"
  3. )
  4. func rangeBitwiseAnd(m int, n int) int {
  5. bits := uint(0)
  6. for i := n; 0 < i; i, bits = i>>1, bits+1 {
  7. }
  8. and := 0
  9. for mask := 1 << (bits - 1); 1 <= mask && (m&mask) == (n&mask); mask >>= 1 {
  10. and |= (m & mask) // Scan from the highest bit, just like 'longest common prefix'
  11. }
  12. return and
  13. }