Skip to content

Commit 3e18b9a

Browse files
committed
TheAlgorithms#10 Create binary_to_Decimal_Conversion Method in Maths Function #
1 parent 3787b38 commit 3e18b9a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

maths/binary_to_Decimal_conversion

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function binaryToDecimal
3+
* @description Convert the binary to decimal .
4+
* @param {number} binary - The input string
5+
* @return {string} - decimal of binary.
6+
* @example binaryToDecimal('1011') = 11
7+
* @example binaryToDecimal('1110') = 14
8+
*/
9+
10+
function binaryToDecimal(binary: string): number {
11+
let decimal: number = 0;
12+
let power: number = 0;
13+
for (let i = binary.length - 1; i >= 0; i--) {
14+
if (binary[i] === '1') {
15+
decimal += Math.pow(2, power);
16+
}
17+
power++;
18+
}
19+
return decimal;
20+
}
21+
22+
23+
const binary: string = '1011';
24+
const decimal: number = binaryToDecimal(binary);
25+
console.log(`The decimal representation of ${binary} is ${decimal}`);

0 commit comments

Comments
 (0)