Problems › JavaScript › patterns
Which is the lowest flag switched on
A permissions field packs each right into its own bit. An audit reports the position of the lowest right that is granted.
- Bits are numbered from 0, starting at the least significant end.
- Return the position of the lowest bit that is set.
- A field with nothing granted returns -1.
- The field is never negative.
lowestFlag(rights: int) → int
Where you start
function lowestFlag(rights) {
}
Worked examples
| Call | Result |
|---|---|
lowestFlag(12) | 2 |
lowestFlag(1) | 0 |
lowestFlag(0) | -1 |
lowestFlag(8) | 3 |
Hint
The expression n & -n leaves only the lowest set bit standing. Counting how far that has to shift down gives its position.
Reference solution in JavaScript
function lowestFlag(rights) {
if (rights === 0) return -1;
let position = 0;
let field = rights;
while ((field & 1) === 0) {
field >>= 1;
position += 1;
}
return position;
}