easy +10 pts

Rotate Bits Left

Rotate the bits of an integer to the left by a given number of positions.

Write a function `rotate_left(x: int, n: int) -> int` that rotates the bits of a non-negative integer `x` to the left by `n` positions. Assume that `x` is represented using **8 bits** (i.e., values from 0 to 255). The rotation should be within these 8 bits, meaning bits shifted out from the most significant side reappear at the least significant side. The parameter `n` is a non-negative integer; if `n` is larger than 8, it should wrap around (e.g., rotating by 8 returns the original number, rotating by 9 is same as rotating by 1). The function should return the resulting 8-bit integer. **Important:** Your implementation must operate on 8-bit numbers only. Use bitwise operations (`<<`, `>>`, `&`, `|`) and handle the wrap-around correctly. Do not use any external libraries. **Examples:** - `rotate_left(0b00001111, 4)` returns `0b11110000` (i.e., 240). - `rotate_left(0b10000001, 1)` returns `0b00000011` (i.e., 3). - `rotate_left(0b10101010, 2)` returns `0b10101010` (i.e., 170). - `rotate_left(255, 3)` returns `255` (all bits set remain the same).

Constraints

- `0 <= x <= 255` (8-bit unsigned integer) - `0 <= n <= 10^9` (large values possible, but the rotation wraps within 8 bits) - Time complexity: O(1) expected (or at most constant in the number of bits).

Example

['>>> rotate_left(0b00001111, 4)\n240', '>>> rotate_left(0b10000001, 1)\n3', '>>> rotate_left(0b10101010, 2)\n170', '>>> rotate_left(255, 3)\n255']
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

First reduce n modulo 8, then shift left by that amount and OR with the bits that wrapped around.
The bits that fall off the left can be obtained by shifting right by `(8 - n)` after masking to 8 bits.
After shifting left, apply a mask `& 0xFF` to keep only the lower 8 bits.
If n is a multiple of 8, return x unchanged.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.