Implement the binaryStringToDecimal method that converts a binary string into its decimal integer value.

The input contains a string binary made of binary digits 0 and 1. Your task is to convert this binary number into its decimal integer value.

Each digit contributes based on its position from right to left. For example, 101 means 1×4 + 0×2 + 1×1, so the answer is 5.

Example 1

Input
binary (string) = 101
Returns (int) 5

Example 2

Input
binary (string) = 1111
Returns (int) 15

Example 3

Input
binary (string) = 0
Returns (int) 0

Read the binary string from left to right and build the decimal value step by step.

Whenever a new binary digit is read, multiply the current decimal value by 2 and add the current digit. This works because moving one position in binary is the same as shifting the value left by one bit.

Pseudocode:

function binaryStringToDecimal(binary):
    decimal = 0
    for each character ch in binary:
        digit = numeric value of ch
        decimal = decimal * 2 + digit
    return decimal
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.