Previous Year Problem For Converting a Binary to Decimal Number
EDIT: This problem luckily came in the end sems too ;)
So, I had seen this problem for doing the conversion as mentioned in the title, and I was thinking about the possible solutions. One of the approaches can be to use the number only which will be passed to a function but I thought of converting it to a string, and yes not to mention, you can pass an int to the function instead of a string, but you will need to convert it to a string and then work on that string as depicted, in the code pasted below.
Cvkkt Xjydib :)
#include <iostream>
#include<cstdlib>
#include<vector>
#include<math.h>
#include<string>
using namespace std;
/*
*
* This program is contributed by Himesh Singh Chauhan
*
*/
int bin_to_dec(string s){
int itr=0;
int ans=0;
int s_size=s.size();
int number=stoi(s);
for(int i=s_size-1;i>=0;i--){
int num;
/*There was some cryptic error if I tried to convert a char
*to an int
*/
// char c=s[i];
// num=atoi(c);
int ascii_num=s[i];
num=ascii_num-48;
ans+=pow(2,itr) *num;
itr++;
}
return ans;
}
int main(){
cout<<"The answer receiverd from the
bin_to_dec() is "<<bin_to_dec("11100111");
return 0;
}
Comments
Post a Comment