Bitwise Flags for Permissions

Hard ⏱ 18 min 26% acceptance ★★★★☆ 4.4
A permission system encodes READ=1, WRITE=2, EXECUTE=4 as bit flags combined with |. Write a function has_permission(flags, permission) that returns True if permission's bit is set within flags, using the bitwise AND operator &. Also write grant(flags, permission) that returns a new flags value with permission's bit added via bitwise OR |.

Examples

Example 1
Input
has_permission(1 | 4, 4)
Output
True
Explanation

EXECUTE (4) bit is present in 5 (0b101).

Example 2
Input
has_permission(1, 2)
Output
False
Explanation

WRITE (2) bit is not present in 1 (0b001).

Example 3
Input
grant(1, 2)
Output
3
Explanation

1 | 2 = 3 (0b011), READ and WRITE both set.

Constraints

  • flags and permission are non-negative integers representing bit combinations.

Topics

Operatorsbitwise operators

Companies

CiscoIntelIBM

Hints

Hint 1

`flags & permission == permission` checks that every bit of permission is present in flags.

Hint 2

`flags | permission` sets the new bit without disturbing existing ones.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.