A simple problem

Hey,
So I found an interesting problem which while being simple enough, needs to use some good thinking and features of your language (at least in my opinion). The program reads:


Write a program that accepts a base ten (non-fractional) number at the command line and outputs the binary representation of that number. Sample input is
 
dectobin 120



I've solved it like this (C code):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        printf("Please run the program like this: program_name decimal_number\n");
        return 1;
    }

    int number = atoi(argv[1]);
    int rem = 0;
    int * binary = malloc(sizeof(int)*100);
    int index = 0;
    int i;

    do
    {
        rem = number%2;
        number = number/2;
        binary[index] = rem;
        index++;
    } while(number != 0);

    for(i = index-1; i >= 0; i--)
    {
        printf("%d", binary[i]);
    }

    free(binary);
    
    return 0;
}


(Please point out mistakes if you find any)

How would you solve this?
Last edited on
closed account (3hM2Nwbp)
1
2
3
4
5
6
7
8
#include <iostream>
#include <bitset>
int main()
{
    int i;
    std::cin >> i;
    std::cout << std::bitset<sizeof(int)>(i) << std::endl;
}


Pecked out on phone, so didn't test.
Last edited on
Topic archived. No new replies allowed.