1426. Any-Base Writer

Easy1.5 points estimatedMathsString

A museum label printer can show numbers in any base from binary up to base 36, and the curators need a routine that prepares the text. Given the integer n and the base b, return the representation of n in base b as a string. Digits with values 0 to 9 are written as the characters 0-9 and values 10 to 35 as lowercase letters a-z. A negative n gets a single leading minus sign followed by the digits of its absolute value, there are no leading zeros, and zero is written as "0". Repeated division of the absolute value gives O(log n) time and O(log n) space for the answer.

Example 1

Input:
n = 255, b = 16
Output:
"ff"
Explanation:

255 = 15 * 16 + 15, and both digits are written as the letter f, giving "ff".

Example 2

Input:
n = -5, b = 2
Output:
"-101"
Explanation:

The absolute value 5 is 101 in binary, and the minus sign is put in front.

Constraints

-1015 ≤ n ≤ 1015
2 ≤ b ≤ 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_b |n|)
Space
O(log_b |n|)

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…