easy
0 views

Function decimalToBinary – CTS PATTERN

Fix the logical error in the decimalToBinary function so it correctly prints the binary representation of a given integer.

Understand the Problem

Problem Statement

Fix all logical errors in the given code. The function decimalToBinary(int N) accepts an integer N as input and is supposed to print the binary representation of N. The function compiles successfully but fails to produce the correct output due to a logical error. Debug the program to make it work correctly.

Constraints

  • Input integer N must be greater than 0 (N > 0)
  • The function should recursively convert the decimal number to binary
  • Output should be the binary representation printed directly
  • No additional libraries or main function required

Examples

Example 1
Input
5
Output
101
Explanation

The binary representation of decimal 5 is 101. The recursive calls work as: decimalToBinary(5) → decimalToBinary(2) → decimalToBinary(1) → decimalToBinary(0). On return: print 1%2=1, 2%2=0, 5%2=1, resulting in 101.

Example 2
Input
8
Output
1000
Explanation

The binary representation of decimal 8 is 1000. The recursive calls work as: decimalToBinary(8) → decimalToBinary(4) → decimalToBinary(2) → decimalToBinary(1) → decimalToBinary(0). On return: print 1%2=1, 2%2=0, 4%2=0, 8%2=0, resulting in 1000.

Solution

void decimalToBinary(int N){
    if(N>0){
        decimalToBinary(N/2);
        printf("%d",N%2);
    }
}
Time:O(log n) - The number of recursive calls is proportional to the number of bits in the binary representation, which is log₂(n)
Space:O(log n) - Due to the recursive call stack depth, which is also proportional to the number of bits
Approach:

The original code had a return 0; statement at the end, which is incorrect since the function is declared as void. The corrected version:

  • Checks if N > 0 (base case)
  • Recursively calls decimalToBinary(N/2) to process the higher bits
  • Prints N%2 to output the current bit
  • Does not return any value since it's a void function

The recursive approach naturally handles the bit ordering by printing remainders on the way back up the call stack.

Visual Explanation

Loading diagram...
Function decimalToBinary – CTS PATTERN | Letuscrack