Drill

ProblemsC# › patterns

Which is the lowest flag switched on

mediumpatternsBit manipulationMathC#

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

LowestFlag(rights: int) → int

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public int LowestFlag(int rights) {
    
}

Worked examples

CallResult
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 C#
public int LowestFlag(int rights) {
    if (rights == 0) return -1;
    int position = 0, field = rights;
    while ((field & 1) == 0) {
        field >>= 1;
        position++;
    }
    return position;
}

The same problem in another language

More patterns problems in C#