I - Binary to Decimal (NBUT 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
无
文章翻译:
无聊的三神得到一个无聊的问题。
所以你必须把一个二进制数转换成小数。
输入
有muti-case。
对于每个案例,有一个二进制数,二进制数的长度小于32,和二进制数没有pre-zero(前导零)。
输出
对于每个二进制数,打印十进制数。小数小于2^31 - 1。
样例输入
1
10
11
样例输出
1
2
3
提示
无
思路:
以”1101”为例。
(1)先计算出最右侧的“1”, sum(“1”) = 1
(2)再计算出最右侧的“01”,并且要用到上次计算的结果。sum(“01”) = sum(“0”) + sum(“1”) = 1
(3)再计算出最右侧的“101”,并且要用到上次计算的结果。sum(“101”) = sum(“1”) + sum(“01”) = 4 + 1 = 5
(4)最后计算出“1101”,并且要利用上次计算的结果。sum(“1101”) = sum(“1”) + sum(“101”) = 8 + 5 = 13
程序分析:
(1)for(; pos >= 0; pos–)
这里第一个表达式没有内容,那是因为在上一步已经赋值了,这里可以省略。
(2)sum += (str[pos] -‘0’) * j 等价于 sum = sum + (str[pos] - ‘0’) * j
j = 2 等价于 j = j 2
(3)数组的下标是从左往右递增的。
例1:str[] = “abcde”,则str[0] = ‘a’, str[1] = ‘b’, str[2] = ‘c’, str[3] = ‘d’, str[4] = ‘e’
例2:str[] = “1101”,则str[0] = ‘1’,str[1] = ‘1’, str[2] = ‘0’, str[3] = ‘1’
二进制与数组相反,二进制的最低位在最右边,最高位在最左边。十进制也是如此。
比如二进制1101,第0位的值是1,第1位的值是0,第2位的值是1,第3位的值是1。
程序中的for采用了从高位向低位递减,就是因为二进制与数组的下标顺序相反。
(4)for的计算过程
刚开始时,pos = strlen(“1101”) - 1 = 4 - 1 = 3
① 第1 次循环,pos = 3,str[pos] - ‘0’ = ‘1’ - ‘0’ = 49 - 48 = 1, sum = sum + 1 * j = 0 + 1 * 1 = 1, j = j * 2 = 1 * 2 = 2, pos自减后变为2
② 第2次循环,pos = 2, str[pos] - ‘0’ = ‘0’ - ‘0’= 48 - 48 = 0,sum = sum + 0 * j = 1 + 0 * 2 = 1, j = j * 2 = 2 * 2 = 4,pos自减后变为1
③ 第3次循环,pos = 1, str[pos] - ‘0’ = ‘1’ - ‘0’= 49 - 48 = 1,sum = sum + 1 * j = 1 + 1 * 4 = 5, j = j * 2 = 4 * 2 = 8,pos自减后变为0
④ 第4次循环,pos = 0, str[pos] - ‘0’ = ‘1’ - ‘0’= 49 - 48 = 1,sum = sum + 1 * j = 5 + 1 * 8 = 13, j = j * 2 = 8 * 2 = 16,pos自减后变为-1,循环结束。
所以,最终的结果就是13
AC代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <math.h>
#include <algorithm>
#define M 1000
using namespace std;
char s[M];
int main()
{
while(~scanf("%s",s))
{
int sum=0;
int j=1;
int pos=strlen(s)-1;
for(; pos>=0; pos--)
{
sum+=(s[pos]-'0')*j;
j*=2;
}
printf("%d\n",sum);
}
return 0;
}
另一种AC代码:
#include <iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int temp;
char s[100];
char ss;
int main()
{
while(~scanf("%s",s))
{
int sum=0;
temp=1;
int len=strlen(s);
for(int i=len-1;i>=0;i--)
{
int a=s[i]-'0';
sum+=a*temp;
temp<<=1;
}
printf("%d\n",sum);
}
return 0;
}