![]() |
Decimal numbers are a base 10 number system which uses 10 digits from 0 to 9 and hexadecimal numbers are a base 16 number system which uses 16 digits, numbers from 0 to 9, and letters from A to F. We are given a hexadecimal number as input we have to convert it into decimal in JavaScript and print the result. Example:Input: 1A Below are the methods to convert Hexadecimal to Decimal: Using parseInt() FunctionIn this approach, there is an inbuilt function parseInt which will convert the hexadecimal number into its decimal equivalent. Use the ‘parseInt’ function with base 16 to convert hexadecimal to decimal to convert the hexadecimal string to its decimal equivalent. Example: Demonstration of converting of hexadecimal to decimal using the inbuilt parseInt().
Output Decimal equivalent of 2A is 42 Time Complexity: O(n). Space Complexity: O(1). Using Number() FunctionIn this approach, we will use the built-in JavaScript function Number() to convert the concatenated string to a decimal number. JavaScript recognizes the hexadecimal format when the “0x” prefix is present inside the Number() function. We will return the decimal equivalent of the hexadecimal input. Example: Demonstration of converting hexadecimal to decimal using the Number() function.
Output Decimal equivalent of 1A is 26 Time Complexity: O(n). Space Complexity: O(1). Using Iterative MethodIn this approach, we will convert the hexadecimal to its decimal equivalent by first converting the current (each) hexadecimal digit to its decimal equivalent using the ‘parseInt’ inbuilt function and then update the decimal value by multiplying by 16 and adding the decimal value of the current digit. Example: Below is the conversion of hexadecimal to decimal by iterating through each character of a hexadecimal string.
Output The Decimal equivalent of 1A is : 26 Time Complexity: O(n) Space Complexity: O(1) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |