Challenge: Binary to Decimal

Lab C Advanced 30 points

Read a binary number as text (only 0s and 1s, up to 30 digits) and print its value in decimal. Then print the same value back in binary, to check.

Input

One word of 0s and 1s.

Output

Decimal: D
Binary: B

(B has no leading zeros; for 0 print 0.)

Example

Input

1011

Output

Decimal: 11
Binary: 1011
Sample input available Sample output available
Editor
C

Hints

Read left to right: value = value * 2 + digit.

bits[i] - '0' turns '0'/'1' into 0/1.

To go back, collect v % 2 while dividing v by 2, then print those digits in reverse.

Solution explanation

Each new binary digit doubles what we had and adds itself. Going back, % 2 gives the last binary digit and / 2 removes it.

Show solution
#include <stdio.h>

int main() {
    char bits[31];
    scanf("%s", bits);
    int value = 0;
    for (int i = 0; bits[i] != '\0'; i++) {
        value = value * 2 + (bits[i] - '0');
    }
    printf("Decimal: %d\n", value);

    char out[32];
    int len = 0;
    int v = value;
    if (v == 0) {
        out[len] = '0';
        len++;
    }
    while (v > 0) {
        out[len] = '0' + v % 2;
        len++;
        v /= 2;
    }
    printf("Binary: ");
    for (int i = len - 1; i >= 0; i--) {
        printf("%c", out[i]);
    }
    printf("\n");
    return 0;
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD