# Decimal-to-Binary Conversion Challenge Solution

```#include <iostream>
#include <math.h>
#include <ctype.h>

using namespace std;

int dectobin(int dec, int power_of_two)
{
if(dec == 0)
{
cout<<"0";
}
else if(dec/(int)pow(2, power_of_two))
{
int remainder = dectobin(dec, power_of_two+1);
if(remainder/(int)pow(2, power_of_two))
{
cout<<"1";
return remainder - (int)pow(2, power_of_two);
}
else
{
cout<<"0";
return remainder;
}
}
else
{
return dec;
}
}

int main(int argc, char *argv[])
{
if(argc != 2)
{
cout<<"Input is of format 'dectobin num'";
return 1;
}
dectobin(atoi(argv[1]), 0);
}
```

The logic behind the program is to find the largest power of two that fits in the decimal number; this is the first one output in the decimal number. The remainder is returned down the recursive chain, and if the current power of two at each function call fits within the remainder, then the function outputs a 1 and returns the remainder minus the amount accounted for by that place in the binary number. Otherwise a 0 is output as a placeholder and the remainder is returned to allow it to be checked against the next smallest power of two.

Many other solutions exist! If yours doesn't match the Cprogramming.com key, but it still works, let us know and we'll upload it as an alternative answer.

Alternate Methods

Solution using bitwise operators submitted by Rohan Dighe.

Several solutions posted to the site's message board

Popular pages