Drill

ProblemsPython › patterns

Which is the lowest flag switched on

mediumpatternsBit manipulationMathPython

A permissions field packs each right into its own bit. An audit reports the position of the lowest right that is granted.

lowest_flag(rights: int) → int

Solve it in the editor →

Where you start

def lowest_flag(rights: int) -> int:
    

Worked examples

CallResult
lowest_flag(12)2
lowest_flag(1)0
lowest_flag(0)-1
lowest_flag(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 Python
def lowest_flag(rights: int) -> int:
    if rights == 0:
        return -1
    position = 0
    field = rights
    while field & 1 == 0:
        field >>= 1
        position += 1
    return position

The same problem in another language

More patterns problems in Python