How to use Iterative Method In Javascript
In 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.
// Define the function
function hexadeciToDeci(hex) {
// Initialize Variable
let decimal = 0;
for (let i = 0; i < hex.length; i++) {
// Convert the current hexadecimal digit
let digit = parseInt(hex[i], 16);
// Update the decimal value by multiplying by 16
// Add the decimal value of the current digit
decimal = decimal * 16 + digit;
}
return decimal;
}
// hexadecimal number
const hexadecimalNumber = "1A";
const decimalEqui = hexadeciToDeci(hexadecimalNumber);
console.log(" The Decimal equivalent of",
hexadecimalNumber, "is : ", decimalEqui);
Output
The Decimal equivalent of 1A is : 26
Time Complexity: O(n)
Space Complexity: O(1)
JavaScript Program to Convert Hexadecimal to Decimal
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
Output: 26
Below are the methods to convert Hexadecimal to Decimal:
Table of Content
- Using parseInt() Function
- Using Number() Function
- Using Iterative Method