forked from TheAlgorithms/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
TheAlgorithms#10 Create binary_to_Decimal_Conversion Method in Maths …
…Function #
- Loading branch information
1 parent
3787b38
commit 3e18b9a
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`); |