JavaScript: Convert Binary to Decimal using recursion
JavaScript Function: Exercise-11 with Solution
Binary to Decimal Conversion
Write a JavaScript program to convert binary number (positive) to decimal number using recursion.
Sample Solution-1:
JavaScript Code:
// Recursive function to convert a binary number to decimal
const binaryToDecimal = (binaryString, index = 0) => {
// Base case: if the string is empty, return 0
if (index === binaryString.length) {
return 0;
}
// Get the current binary digit (0 or 1)
const currentDigit = parseInt(binaryString[index]);
// Recursive step: convert the rest of the string and update the result
const restDecimal = binaryToDecimal(binaryString, index + 1);
const currentDecimal = currentDigit * Math.pow(2, binaryString.length - index - 1);
return currentDecimal + restDecimal;
};
// Test the function with different binary numbers
console.log(binaryToDecimal("1"));
console.log(binaryToDecimal("0"));
console.log(binaryToDecimal("10"));
console.log(binaryToDecimal("101"));
Output:
1 0 2 5
Flowchart:
Live Demo:
See the Pen javascript-recursion-function-exercise-11 by w3resource (@w3resource) on CodePen.
Sample Solution-2:
JavaScript Code:
// Recursive function to convert a binary number to decimal
const binaryToDecimal = (binaryString, index = 0) => {
// Base case: if the string is empty, return 0
if (index === binaryString.length) {
return 0;
}
// Get the current binary digit (0 or 1)
const currentDigit = parseInt(binaryString[index]);
// Recursive step: convert the rest of the string and update the result
const restDecimal = binaryToDecimal(binaryString, index + 1);
const currentDecimal = currentDigit * Math.pow(2, binaryString.length - index - 1);
return currentDecimal + restDecimal;
};
// Test the function with different binary numbers
console.log(binaryToDecimal("1"));
console.log(binaryToDecimal("0"));
console.log(binaryToDecimal("10"));
console.log(binaryToDecimal("101"));
Output:
1 0 2 5
Flowchart:
Live Demo:
See the Pen javascript-recursion-function-exercise-11 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Check a string for palindromes using recursion.
Next:Binary Search Algorithm using recursion.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics