problem no 8:Binary number to decimal number

 QUESTION:

Given a Binary Number in the string format B, find its decimal equivalent.
 

Example 1:

Input: B = 10001000
Output: 136

Example 2:

Input: B = 101100
Output: 44

 

 

ANSWER:

 

    int binary_to_decimal(string str)
        {
            vector<char> vec;
            int result;
            for(int i=str.size()-1;i>=0;i--)
            {
                vec.push_back(str[i]);
            }
            for(int i=0;i<vec.size();i++)
            {
                if(vec[i]=='0' || vec[i]=='1')
                {
                    if(vec[i]=='1')
                    {
                        result=result+pow(2,i);
                    }
                }
            }
            return result;
           
        }

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.