1838. Digit Carousel
A combination lock shows the digits of n on a ring, and each turn moves the last digit to the front. A positive k means k turns to the right, so the last k digits move to the front. A negative k means -k turns to the left, so the first digits move to the back. For example, 562984 turned right by 2 becomes 845629, and turned left by 3 becomes 984562.
Return the new number as an integer. If the rotation puts zeros at the front, they simply disappear, so 1002 turned right by 2 gives 0210, which is the number 210. The value of k can be much larger than the number of digits. Aim for O(log n) time and O(1) extra space.
Example 1
- Input:
- n = 562984, k = 2
- Output:
- 845629
- Explanation:
The last two digits, 84, move to the front.
Example 2
- Input:
- n = 562984, k = -3
- Output:
- 984562
- Explanation:
The first three digits, 562, move to the back.
Example 3
- Input:
- n = 1002, k = 2
- Output:
- 210
- Explanation:
The rotation gives 0210, which is the number 210.
Constraints
0 ≤ n ≤ 109 - 1
-109 ≤ k ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(log n)
- Space
- O(1)