Skip to content

Commit f3bed0e

Browse files
realDuYuanChaogithub-actions
andauthored
decimal to binary using recursion (#575)
* add decimal_to_binary_recursion.c * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent ff2e7a3 commit f3bed0e

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
* [Binary To Octal](https://github.com/TheAlgorithms/C/blob/master/conversions/binary_to_octal.c)
1313
* [C Atoi Str To Integer](https://github.com/TheAlgorithms/C/blob/master/conversions/c_atoi_str_to_integer.c)
1414
* [Decimal To Binary](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_binary.c)
15+
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_binary_recursion.c)
1516
* [Decimal To Hexa](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_hexa.c)
1617
* [Decimal To Octal](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_octal.c)
1718
* [Decimal To Octal Recursion](https://github.com/TheAlgorithms/C/blob/master/conversions/decimal_to_octal_recursion.c)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @file
3+
* @brief Convert decimal to binary using recursion algorithm
4+
*/
5+
#include <assert.h>
6+
7+
/**
8+
* Decimal to binary using recursion algorithm.
9+
* For example, if number = 5, the function returns the decimal integer 101.
10+
* @param number positive integer number to convert
11+
* @returns integer with digits representing binary value representation of
12+
* number.
13+
*/
14+
int decimal_to_binary(unsigned int number)
15+
{
16+
return number == 0 ? 0 : number % 2 + 10 * decimal_to_binary(number / 2);
17+
}
18+
19+
/** Test function */
20+
void test()
21+
{
22+
const int sets[][2] = {
23+
{0, 0}, {1, 1}, {2, 10}, {3, 11}, {4, 100}, {6, 110}, {7, 111},
24+
/* add more data sets to test */
25+
};
26+
27+
for (int i = 0, size = sizeof(sets) / sizeof(sets[0]); i < size; ++i)
28+
{
29+
assert(decimal_to_binary(sets[i][0]) == sets[i][1]);
30+
}
31+
}
32+
33+
/** Driver Code */
34+
int main()
35+
{
36+
test();
37+
return 0;
38+
}

0 commit comments

Comments
 (0)