Binary to Decimal

Easy
0/40
Average time to solve is 15m
27 upvotes
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’.
Detailed explanation ( Input/output format, Notes, Images )

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

Sample Input 1:

2
7
1010101
4
1011

Sample Output 1:

85
11

Explanation of Sample Input 1:

Test case 1:

The Decimal equivalent of the Binary number ā€œ1010101ā€ is 85.

Test case 2:
The Decimal equivalent of the Binary number ā€œ1011ā€ is 11.

Sample Input 2:

2
4
1111       
1
0

Sample Output 2:

15
0

Explanation of Sample Input 2:

Test case 1:

The Decimal equivalent of the Binary number ā€œ1111ā€ is 15.

Test case 2:

The Decimal equivalent of the Binary number ā€œ0ā€ is 0.
Hint

Think of the relationship between a binary number and its’s equivalent decimal number.

Approaches (1)
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’.
Time Complexity

O(N), where ā€˜N’ is the given size of the given string.

 

As we will only be traversing the given string completely. Hence the overall time complexity is O (N).

Space Complexity

O(1) 

 

As we are not using any extra space hence the overall space complexity will be constant.

Code Solution
(100% EXP penalty)
Binary to Decimal
Full screen
Console