Problem of the day
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
2
7
1010101
4
1011
85
11
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.
2
4
1111
1
0
15
0
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.
Think of the relationship between a binary number and itsās equivalent decimal number.
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ā.
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).
O(1)
As we are not using any extra space hence the overall space complexity will be constant.