![]() |
VOOZH | about |
Given a number and its base, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. The value of A is 10, the value of B is 11 and so on. Write a function to convert the number to decimal.
Examples:
Input number is given as string and output is an integer.
Input: str = "1100", base = 2
Output: 12
Input: str = "11A", base = 16
Output: 282
Input: str = "123", base = 8
Output: 83
We strongly recommend you to minimize your browser and try this yourself first.
We can always use the below formula to convert from any base to decimal.
"str" is input number as a string
"base" is the base of the input number.
Decimal Equivalent is,
1*str[len-1] + base*str[len-2] + (base)2*str[len-3] + ...
Below is implementation of above formula.
Decimal equivalent of 11A in base 16 is 282
Time Complexity: O(N) n represents the length of string
Auxiliary Space: O(1)
How to do reverse?
Let the given input decimal number be "inputNum" and target base be "base". We repeatedly divide inputNum by base and store the remainder. We finally reverse the obtained string. Below is C implementation.
Equivalent of 282 in base 16 is 11A
Time Complexity: O(logbasen) where 'n' is the input number and 'base' is the base to which the number is to be converted.
Auxiliary Space: O(logbasen)
12
Time complexity: O(N) Convert input number is given base by repeatedly inputNum dividing it by base and taking remainder takes O(n) complexity
Auxiliary Space: O(1)