Skip to content

Instantly share code, notes, and snippets.

@munguial
Created April 24, 2020 05:01
Show Gist options
  • Save munguial/b932d36e49878a04ab60c4697e5b1c8f to your computer and use it in GitHub Desktop.
Save munguial/b932d36e49878a04ab60c4697e5b1c8f to your computer and use it in GitHub Desktop.
Day 23 - Bitwise AND of Numbers Range
# https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/531/week-4/3308/
class Solution {
fun rangeBitwiseAnd(m: Int, n: Int): Int {
var mShifts = 0
var nShifts = 0
var M = m
var N = n
while (M > 0) {
M = M shr 1
mShifts += 1
}
while (N > 0) {
N = N shr 1
nShifts += 1
}
if (mShifts != nShifts) {
return 0
}
var i = mShifts - 1
var result = 0
while (i >= 0) {
val mask = 1 shl i
if (m and mask == n and mask) {
result += m and mask
} else {
break
}
i -= 1
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment