单点时限: 2.0 sec
内存限制: 256 MB
定义一个函数 b2i
,将一个字符串表示的 2 进制无符号数转换成一个无符号 10 进制数。
提示
例如:01
对应 1,111
对应 7,0000
对应 0。
只需按要求写出函数定义,并使用给定的测试程序测试你所定义函数的正确性。
不要改动测试程序。
测试正确后,将测试程序和函数定义一起提交到考试系统。
/***************************************************************/
/* */
/* DON'T MODIFY main function ANYWAY! */
/* */
/***************************************************************/
#include <stdio.h>
unsigned b2i(char s[])
/* PreCondition: s 是由 0 和 1 组成的字符串,且字符串长度不超 32
PostCondition: 返回与字符串 s 对应的十进制数
*/
{ //TODO: your function definition
}
/***************************************************************/
#define N 32
int main()
{ char s[N+1];
scanf("%s",s);
//********** b2i is called here ********************
printf("%u\n",b2i(s));
//**************************************************
return 0;
}
随心所欲用栈实现的,属于是想到哪就写到哪了=.=:
#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;
}