Skip to content

Commit

Permalink
decimal to binary using recursion (TheAlgorithms#575)
Browse files Browse the repository at this point in the history
* add decimal_to_binary_recursion.c

* updating DIRECTORY.md

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
  • Loading branch information
realDuYuanChao and github-actions authored Jul 31, 2020
1 parent ff2e7a3 commit f3bed0e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* [Binary To Octal](https://github.com/TheAlgorithms/C/blob/master/conversions/binary_to_octal.c)
* [C Atoi Str To Integer](https://github.com/TheAlgorithms/C/blob/master/conversions/c_atoi_str_to_integer.c)
* [Decimal To Binary](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_binary.c)
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_binary_recursion.c)
* [Decimal To Hexa](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_hexa.c)
* [Decimal To Octal](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_octal.c)
* [Decimal To Octal Recursion](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_octal_recursion.c)
Expand Down
38 changes: 38 additions & 0 deletions conversions/decimal_to_binary_recursion.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* @file
* @brief Convert decimal to binary using recursion algorithm
*/
#include <assert.h>

/**
* Decimal to binary using recursion algorithm.
* For example, if number = 5, the function returns the decimal integer 101.
* @param number positive integer number to convert
* @returns integer with digits representing binary value representation of
* number.
*/
int decimal_to_binary(unsigned int number)
{
return number == 0 ? 0 : number % 2 + 10 * decimal_to_binary(number / 2);
}

/** Test function */
void test()
{
const int sets[][2] = {
{0, 0}, {1, 1}, {2, 10}, {3, 11}, {4, 100}, {6, 110}, {7, 111},
/* add more data sets to test */
};

for (int i = 0, size = sizeof(sets) / sizeof(sets[0]); i < size; ++i)
{
assert(decimal_to_binary(sets[i][0]) == sets[i][1]);
}
}

/** Driver Code */
int main()
{
test();
return 0;
}

0 comments on commit f3bed0e

Please sign in to comment.