BUPT-homework/pset6/4-binary.c

34 lines
445 B
C
Raw Normal View History

2021-11-01 20:25:24 +08:00
#include <stdio.h>
// Function prototypes
int bin2dec(int n);
int pow2(int n);
int main(void) {
// Initialize variables
int n;
scanf("%d", &n);
printf("%d\n", bin2dec(n));
return 0;
}
int bin2dec(int n) {
int ans = 0;
int loc = 0;
while (n != 0) {
ans += pow2(loc) * (n % 10);
n /= 10;
loc++;
}
return ans;
}
int pow2(int n) {
int ans = 1;
for (int i = 0; i < n; i++) {
ans *= 2;
}
return ans;
}