Part 2 of 28 in Maths - Beginner set 01  

Convert from binary to decimal by admin

Problem statement

Given the binary representation of a number, convert it to its decimal form.

Input

The first line will contain an integer T = number of test case. Next T lines will contain a string of size 1 to 30 characters representing the binary form of a number.

Output

For each string (binary form), print on a single line, the number in decimal number system.

Sample Input
4
101
100
1011
1111
Sample Output
5
4
11
15
1) See constraints. Binary string can be up to 30 characters. Are you  taking input in integer variable that can hold only 10 digits or long integer than can hold about 19 digits?

 Are you good for 10000000000000000000000000 ? 

If you're not familiar with the binary number system, check out the video lesson to get a good understanding of how binary numbers work and also the way in which we can convert a binary number to decimal. We will discuss the code to implement the algorithm shown in the video.

When we try to input an integer using cin, the library code always interprets the integer as decimal. So when we want to read a 30-digit binary number, the library code will look at it as a 30-digit decimal number if we try to read it as an int This will overflow the capacity of an int – therefore we need to read the input as a string or char[]

        // Read the binary number
        string binary_number; cin>>binary_number;

Since the binary number only has up to 30 digits, we can use the int data type to do all our calculations. This is because an int can store all numbers less than 231 whereas a 30 digit binary number will have values less than 230. So we can safely use the int data type.

Our binary number is stored as a string, so there is a slight problem in accessing the digits of the number. When dealing with numbers, when we say 0th place, we mean the right-most place. However, when we are dealing with strings, when we say 0th place, we mean the left-most character. It is important to keep this difference in mind while solving the problem. There are many ways to get around this:

  1. We can reverse the string to begin with (the approach taken in the featured solution)
  2. We could calculate from right-to-left itself and multiply the whole number by 2 every time we encounter a new digit
  3. When we're looking at the x-th digit in a number, we can look for the x-th character in the string from its right-side

Here's the code to reverse the string

...
#include<algorithm>   // To import string reverse algorithm

using namespace std;  // We can avoid using std:: prefix
                      // for all imported functions & classes
        
        ...

        // Strings are read from left to right
        // however numbers are processed from right to left
        // Reversing the string will fix this
        // so that 0th digit of string = 0th digit of number
        reverse(binary_number.begin(), binary_number.end());

We can now simply iterate through the digits as explained in the video lesson

        // Initialize our decimal number
        int decimal_number = 0;
        // We will calculate powers of 2 on the fly
        // Initially we need 2 to the power 0th place = 1
        int pow2 = 1;
        
        // For each place in the string
        for(int place = 0; place < binary_number.size(); place++) {
            // Get the character at the place
            char digit = binary_number[place];
            
            // Get the binary value (0 or 1) from the character
            int digit_value = digit - '0';

            // add the value of this digit multiplied by place value
            decimal_number += digit_value * pow2;
            
            // Update the power of 2 for the next place
            pow2 *= 2;
        }

While slightly more complicated for beginners, approach 2 leads to a shorter and more elegant solution. The key changes can be seen in the code snippet below.

        // Read the binary number
        string binary_number; cin>>binary_number;

        // Initialize our decimal number
        int decimal_number = 0;

        // For each place in the string
        for(int place = 0; place < binary_number.size(); place++) {
            // Get the character at the place
            char digit = binary_number[place];
            
            // Get the binary value (0 or 1) from the character
            int digit_value = digit - '0';

            // Update the decimal number
            decimal_number = decimal_number * 2 + digit_value;
        }

editorial written by harsha_s

#include<iostream>    // To import cin and cout
#include<string>      // To import the string class
#include<algorithm>   // To import string reverse algorithm

using namespace std;  // We can avoid using std:: prefix
                      // for all imported functions & classes

int main() {
    int test_cases; cin>>test_cases; // Read the number of test cases
    
    while(test_cases-- > 0) {        // In a loop, process each test case

        // Read the binary number
        string binary_number; cin>>binary_number;
        
        // Strings are read from left to right
        // however numbers are processed from right to left
        // Reversing the string will fix this
        // so that 0th digit of string = 0th digit of number
        reverse(binary_number.begin(), binary_number.end());
        
        // Initialize our decimal number
        int decimal_number = 0;
        // We will calculate powers of 2 on the fly
        // Initially we need 2 to the power 0th place = 1
        int pow2 = 1;
        
        // For each place in the string
        for(int place = 0; place < binary_number.size(); place++) {
            // Get the character at the place
            char digit = binary_number[place];
            
            // Get the binary value (0 or 1) from the character
            int digit_value = digit - '0';

            // add the value of this digit multiplied by place value
            decimal_number += digit_value * pow2;
            
            // Update the power of 2 for the next place
            pow2 *= 2;
        }
        cout<<decimal_number<<endl;
    }
    
    return 0;
}

featured solution by harsha_s



To try out your code



Sign in

Sign up