シングルポイント制限時間: 2.0秒
メモリ制限: 256 MB
b2i
文字列で表される符号なし 2 進数を符号なし 10 進数に変換する関数を定義します 。
ヒント
例: 01
1 に対応、111
7 に対応、0000
0 に対応。
必要に応じて関数定義を書き出し、指定されたテスト プログラムを使用して定義された関数の正確さをテストするだけです。
テスト手順を変更しないでください。
テストが正しければ、テスト プログラムと関数定義を試験システムに送信します。
/***************************************************************/
/* */
/* 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;
}
作者はスタックを使って好きに実装しているので、思いついたところに書くだけ =.=:
#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;
}