Created
April 24, 2020 05:01
-
-
Save munguial/b932d36e49878a04ab60c4697e5b1c8f to your computer and use it in GitHub Desktop.
Day 23 - Bitwise AND of Numbers Range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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