Binary to Decimal

题目链接:https://ac.2333.moe/Problem/view.xhtml?id=1227
The boring Three-God get a boring question.
So you have to transform a binary number to a decimal.
Input
There are muti-case.
For each case, there are a binary number, the binary number’s length is less than 32, and the binary number have no pre-zero (前导零).
Output
For each binary number, print the decimal numbuer.the decimal number is less than 2^31 - 1.
Sample Input
1
10
11
Sample Output
1
2
3
Hint

题意:这题其实就是要你把二进制数转换为一个十进制数。
. 在这里补一下:
十进制整数转换为二进制整数
十进制整数转换为二进制整数采用"除2取余,逆序排列"法。具体做法是:用2整除十进制整数,可以得到一个商和余数;再用2去除商,又会得到一个商和余数,如此进行,直到商为小于1时为止,然后把先得到的余数作为二进制数的低位有效位,后得到的余数作为二进制数的高位有效位,依次排列起来。
解题思路:把二进制数当字符串,然后直接按下面的方法求。
二进制求十进制的方法:就是把一个有X位的二进制数,从右往左数,每一位依次乘以2的0次方,2的1次方,2的2次方,一直乘到2的X-1次方,然后把这些次方。的结果加起来即可得到最终一个十进制数的结果。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
    char t[34];
    while(~scanf("%s",t))
    {
        int l=strlen(t
        int a[34];
        for(int i=0;i<l;i++)
        {
            a[i]=t[i]-48;//每一个位数减去0的十进制的ASCLL值;
        }
        int x=a[0];
        for(int i=1;i<l;i++)
        {
            x=x*2+a[i];//进制转换;
        }
        printf("%d\n",x);
    }
   return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_43516113/article/details/88991645