Base Converter - Problem
Write functions to convert a number from any base (2-16) to any other base.
Your function should take three parameters:
number: The number to convert (as a string)fromBase: The base of the input number (integer from 2 to 16)toBase: The target base for conversion (integer from 2 to 16)
For bases greater than 10, use uppercase letters A-F to represent digits 10-15.
Note: Handle invalid inputs by returning an empty string.
Input & Output
Example 1 — Binary to Hexadecimal
$
Input:
number = "1010", fromBase = 2, toBase = 16
›
Output:
"A"
💡 Note:
Binary 1010 = 1×8 + 0×4 + 1×2 + 0×1 = 10 in decimal, then 10 in decimal = A in hexadecimal
Example 2 — Decimal to Binary
$
Input:
number = "10", fromBase = 10, toBase = 2
›
Output:
"1010"
💡 Note:
Decimal 10 divided by 2 repeatedly: 10÷2=5 R0, 5÷2=2 R1, 2÷2=1 R0, 1÷2=0 R1, reading remainders backwards gives 1010
Example 3 — Same Base
$
Input:
number = "123", fromBase = 10, toBase = 10
›
Output:
"123"
💡 Note:
Same base conversion returns the original number unchanged
Constraints
- 2 ≤ fromBase, toBase ≤ 16
- 1 ≤ number.length ≤ 30
- number contains only valid digits for fromBase
- Digits 0-9 for values 0-9, letters A-F for values 10-15
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code