Last Updated: 26 Nov, 2020

Binary to Decimal

Easy
Asked in companies
OptumMathworksCapegemini Consulting India Private Limited

Problem statement

Ninja is given a binary number as a string ‘S’ of size ‘N’, he is asked to convert it into its decimal equivalent (as an Integer) and print it.

Note:

A binary string is a string in which all characters are either ‘1’ or ‘0’.

Input Format:

The first line contains an integer 'T' which denotes the number of test cases or queries to be run.

The first line of each test case contains a single integer ‘N’ denoting the size of the given string.

The second line of each test case contains the string ‘S’  .

Output Format:

For each test case, print the corresponding Decimal number (as Integer).

The output of each test case will be printed in a separate line.

Note:

You do not need to input or print anything, as it has already been taken care of. Just implement the given function.

Constraints:

1 <= T <= 5 
1 <= N <= 30

 Where ‘T’ is the total number of test cases and ‘N’ is the size of the given string.

 The second line of each test case contains the string ‘S’.

Time limit: 1 sec

Approaches

01 Approach

The idea here is to keep a variable ‘value’ for storing the decimal value. We start traversing the string from the end and for each digit multiply the digit with the proper power of 2 and add it to the variable ‘value’ and after complete traversal of the string return the variable ‘value’.

 

 Algorithm:

 

  • Let the given string be ‘S’ of size ‘N’.
  • Declare a variable ‘baseVal’ and initialize it’s value to 1.
  • Declare a variable ‘value’ for storing the decimal equivalent of a binary number.
  • Run a loop from ‘i’ = ’N’ - 1 to ‘i’ = 0 ).
    • If ‘S[i]’ == ‘1’
      • Set ‘value’ = ’value’ + ‘base_val’.
    • Do ‘baseVal’ = ‘baseVal’ * 2
  • Return ‘value’.