Write It in Another Base
EasyMath & Geometry
Problem
A debugging console shows integers in any base from 2 to 36. Digits above 9 are written with lowercase letters: a = 10, b = 11, ..., z = 35.
Given an integer value and a base, return value written in that base. Negative values start with -. Zero is written "0".
Example 1
- Input:
- value = 255, base = 16
- Output:
- "ff"
255 = 15 · 16 + 15.
Example 2
- Input:
- value = -10, base = 2
- Output:
- "-1010"
Example 3
- Input:
- value = 0, base = 7
- Output:
- "0"
Constraints
- -10^15 ≤ value ≤ 10^15
- 2 ≤ base ≤ 36
Hint
Show the first hint
The last digit of value in base b is value mod b.
Walkthrough
How to approach it
01Clarify before coding
- Uppercase or lowercase letters? Lowercase, a = 10 up to z = 35.
- How are negatives shown? A leading minus sign on the magnitude, not two's complement.
- Can I use a built-in such as toString(base)? No: write the conversion yourself.
02Brute force
Find the largest power of the base not exceeding value, then subtract multiples of each power from the top down.
Cost: Also O(log_b |value|), but computing powers risks overflow and is easy to get wrong; repeated division is simpler.
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.
This problem is part of Pro.