1846. Reverse in Base B

Easy1.5 points estimatedMathsSimulationNumber Theory3 hints

A puzzle writes a number in some base, reads the digits backwards, and asks for the value of the new digit string in the same base. For example, 12 is 1100 in base 2, and reading it backwards gives 0011, which has the value 3. In base 10 the number 123 becomes 321.

Given n and base, return the value of the reversed digits. Leading zeros of the reversed string do not change its value, and 0 stays 0. Build the answer while taking digits off n with the remainder and integer division by the base, so no string is needed. Aim for O(log n) time and O(1) extra space.

Example 1

Input:
n = 12, base = 2
Output:
3
Explanation:

12 is 1100 in base 2, reversed it is 0011, which equals 3.

Example 2

Input:
n = 123, base = 10
Output:
321
Explanation:

The digits 1, 2, 3 reversed give 321.

Example 3

Input:
n = 0, base = 7
Output:
0
Explanation:

Zero stays zero.

Constraints

0 ≤ n ≤ 1012

2 ≤ base ≤ 36

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)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…