Base Conversion

Medium~15 min

Given a non-negative integer n and a base base (between 2 and 16 inclusive), convert n to its string representation in the given base.

For bases greater than 10, use lowercase letters a-f to represent digit values 10-15. For example:

  • convertBase(255, 16) returns "ff"
  • convertBase(10, 2) returns "1010"
  • convertBase(0, 8) returns "0"

Examples

Example 1
Input: n = 255, base = 16
Output: "ff"
Explanation: 255 = 15 * 16 + 15. The digits are 15 and 15, which are "f" and "f" in hexadecimal.
Example 2
Input: n = 10, base = 2
Output: "1010"
Explanation: 10 = 1*8 + 0*4 + 1*2 + 0*1 = 1010 in binary.
Example 3
Input: n = 0, base = 8
Output: "0"
Explanation: Zero is "0" in any base.

Constraints

  • 0 <= n <= 10^9
  • 2 <= base <= 16
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run