EOJ3170. Binary to decimal conversion

 Single point time limit:  2.0 sec

Memory limit:  256 MB

Define a function  b2ito convert an unsigned binary number represented by a string into an unsigned decimal number.

hint

For example: 01 corresponds to 1, 111 corresponds to 7, 0000 corresponds to 0.

Just write out the function definition as required and test the correctness of your defined function using the given test program.
Do not change the test procedure.
After the test is correct, submit the test program and function definition to the examination system.

/***************************************************************/
/*                                                             */
/*  DON'T MODIFY main function ANYWAY!                         */
/*                                                             */
/***************************************************************/

/* 
   PreCondition:  s 是由 0 和 1 组成的字符串,且字符串长度不超 32
   PostCondition: 返回与字符串 s 对应的十进制数
*/

#include <stdio.h>
unsigned b2i(char s[])
{ 
       //TODO: your function definition
}


#define N 32
int main()
{   char s[N+1];
    scanf("%s",s);

    printf("%u\n",b2i(s));
    return 0;
}

The author uses the stack to implement it as he pleases. I just write wherever I think =.=:

#include <iostream>
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;

unsigned b2i(char s[])
{
	stack<char> st;
	int i=0, level=0;
	char temp;
	unsigned int ret=0;
	while(i < strlen(s)){
		st.push(s[i++]);
	}
	
	while(!st.empty()){
		temp = st.top();
		if(temp == '1'){
			ret += pow(2, level);
		}
		level++;
		st.pop();
	}
	return ret;
}

#define N 32
int main(){   
	char s[N+1];
    scanf("%s",s);
    printf("%u\n",b2i(s));
	return 0;
}

Guess you like

Origin blog.csdn.net/qingxiu3733/article/details/131754550