Skip to content

Commit

Permalink
TheAlgorithms#10 Create binary_to_Decimal_Conversion Method in Maths …
Browse files Browse the repository at this point in the history
…Function #
  • Loading branch information
Preetiraj3697 committed Apr 14, 2023
1 parent 3787b38 commit 3e18b9a
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions maths/binary_to_Decimal_conversion
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @function binaryToDecimal
* @description Convert the binary to decimal .
* @param {number} binary - The input string
* @return {string} - decimal of binary.
* @example binaryToDecimal('1011') = 11
* @example binaryToDecimal('1110') = 14
*/

function binaryToDecimal(binary: string): number {
let decimal: number = 0;
let power: number = 0;
for (let i = binary.length - 1; i >= 0; i--) {
if (binary[i] === '1') {
decimal += Math.pow(2, power);
}
power++;
}
return decimal;
}


const binary: string = '1011';
const decimal: number = binaryToDecimal(binary);
console.log(`The decimal representation of ${binary} is ${decimal}`);

0 comments on commit 3e18b9a

Please sign in to comment.