The Wayback Machine - https://web.archive.org/web/20240717181821/https://www.geeksforgeeks.org/decimal-binary-number-using-recursion/
Open In App

Decimal to binary number using recursion

Last Updated : 01 Mar, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number. 

Examples : 

Input : 7                                                         
Output :111

Input :10
Output :1010

We have discussed one iterative solution in below post. 
Program for Decimal to Binary Conversion
Below is Recursive solution:

findBinary(decimal)
   if (decimal == 0)
      binary = 0
   else
      binary = decimal % 2 + 10 * (findBinary(decimal / 2))

Step-by-step process for a better understanding of how the algorithm works 
Let the decimal number be 10. 
Step 1-> 10 % 2 which is equal-too 0 + 10 * ( 10/2 ) % 2 
Step 2-> 5 % 2 which is equal-too 1 + 10 * ( 5 / 2) % 2
Step 3-> 2 % 2 which is equal-too 0 + 10 * ( 2 / 2 ) % 2
Step 4-> 1 % 2 which is equal-too 1 + 10 * ( 1 / 2 ) % 2
 

Recursion Tree for Decimal to Binary Conversion

C++




// C++ program for decimal to binary
// conversion using recursion
#include <bits/stdc++.h>
using namespace std;
 
// Decimal to binary conversion
// using recursion
int find(int decimal_number)
{
    if (decimal_number == 0)
        return 0;
    else
        return (decimal_number % 2 + 10 *
                find(decimal_number / 2));
}
 
// Driver code
int main()
{
    int decimal_number = 10;
    cout << find(decimal_number);
    return 0;
}
// This code is contributed by shivanisinghss2110


C




// C/C++ program for decimal to binary
// conversion using recursion
#include <stdio.h>
 
// Decimal to binary conversion
// using recursion
int find(int decimal_number)
{
    if (decimal_number == 0)
        return 0;
    else
        return (decimal_number % 2 + 10 *
                find(decimal_number / 2));
}
 
// Driver code
int main()
{
    int decimal_number = 10;
    printf("%d", find(decimal_number));
    return 0;
}


Java




// Java program for decimal to binary
// conversion using recursion
import java.io.*;
 
class GFG
{
     
    // Decimal to binary conversion
    // using recursion
    static int find(int decimal_number)
    {
        if (decimal_number == 0)
            return 0;
             
        else
         
        return (decimal_number % 2 + 10 *
                find(decimal_number / 2));
    }
     
// Driver Code
public static void main(String args[])
{
    int decimal_number = 10;
    System.out.println(find(decimal_number));
}
 
}
 
// This code is contributed by Nikita Tiwari


Python3




# Python3 code for decimal to binary
# conversion using recursion
 
# Decimal to binary conversion
# using recursion
def find( decimal_number ):
    if decimal_number == 0:
        return 0
    else:
        return (decimal_number % 2 + 10 *
                find(int(decimal_number // 2)))
 
# Driver Code
decimal_number = 10
print(find(decimal_number))
 
# This code is contributed
# by "Sharad_Bhardwaj"


C#




// C# program for decimal to binary
// conversion using recursion
using System;
 
class GFG
{
     
    // Decimal to binary conversion
    // using recursion
    static int find(int decimal_number)
    {
        if (decimal_number == 0)
            return 0;
             
        else
         
        return (decimal_number % 2 + 10 *
                find(decimal_number / 2));
    }
     
    // Driver Code
    public static void Main()
    {
         
        int decimal_number = 10;
         
        Console.WriteLine(find(decimal_number));
    }
}
 
// This code is contributed by vt_m


PHP




<?php
// PHP program for decimal to binary
// conversion using recursion
 
// Decimal to binary
// conversion using recursion
function find($decimal_number)
{
    if ($decimal_number == 0)
        return 0;
    else
        return ($decimal_number % 2 + 10 *
                find($decimal_number / 2));
}
 
// Driver Code
$decimal_number = 10;
echo(find($decimal_number));
 
// This code is contributed by Ajit.
?>


Javascript




<script>
 
// Javascript program for decimal to binary
// conversion using recursion
 
// Decimal to binary conversion
// using recursion
function find(decimal_number)
{
    if (decimal_number == 0)
        return 0;
    else
        return ((decimal_number % 2) + 10 *
                find(parseInt(decimal_number / 2)));
}
 
// Driver code
var decimal_number = 10;
document.write( find(decimal_number));
 
// This code is contributed by noob2000.
</script>


Output

1010

Time Complexity: O(log2n), Here n is the decimal_number.
Auxiliary Space: O(1), As constant extra space is used.

The above approach works fine unless you want to convert a number greater than 1023 in decimal to binary. The binary of 1024 is 10000000000 (one 1 and ten 0’s) which goes out of the range of int. Even with long long unsigned as return type the highest you can go is 1048575 which is way less than the range of int. An easier but effective approach would be to store the individual digits of the binary number in a vector of bool.

C++




// C++ program for decimal to binary
// conversion using recursion
#include<bits/stdc++.h>
using namespace std;
 
 
// Function to convert decimal to binary
void deci_to_bin(int x, string & bin_num)
{
   
    // Base Case
    if (x <= 1)
        bin_num += (char)(x + '0');
    else {
       
        // Recursion call
        deci_to_bin(x / 2, bin_num);
       
        // If x is divisible by 2
        if(x%2)
          bin_num += '1';
       
        // otherwise
        else
          bin_num += '0';
    }
}
 
// Driver Code
int main()
{
    string bin_num = "";
    deci_to_bin(1048576, bin_num);
     
    cout<<bin_num;
    return 0;
}


Java




// Java program for decimal to binary
// conversion using recursion
public class Main
{
    static String bin_num = "";
       
    // Function to convert decimal to binary
    static void deci_to_bin(int x)
    {
   
        // Base Case
        if (x <= 1)
            bin_num += (char)(x + '0');
        else {
   
            // Recursion call
            deci_to_bin((int)(x / 2));
   
            // If x is divisible by 2
            if(x%2 != 0)
              bin_num += '1';
   
            // otherwise
            else
              bin_num += '0';
        }
    }
      
    public static void main(String[] args) {
        deci_to_bin(1048576);
        
        System.out.print(bin_num);
    }
}
 
// This code is contributed by divyesh072019.


Python3




# Python3 code for decimal to binary
# conversion using recursion
  
# Decimal to binary conversion
# using recursion
def getbinary(number):
   
    # Base case
    if number == 0:
        return 0
       
     # Recursion call and storing the result
    smallans = getbinary(number // 2)
     
    return number % 2 + 10 * smallans
   
# Driver Code
decimal_number = 1048576
print(getbinary(decimal_number))
  
# This code is contributed
# by "Sarthak Sethi"


C#




// C# program for decimal to binary
// conversion using recursion
using System;
class GFG {
     
    static string bin_num = "";
      
    // Function to convert decimal to binary
    static void deci_to_bin(int x)
    {
  
        // Base Case
        if (x <= 1)
            bin_num += (char)(x + '0');
        else {
  
            // Recursion call
            deci_to_bin((int)(x / 2));
  
            // If x is divisible by 2
            if(x%2 != 0)
              bin_num += '1';
  
            // otherwise
            else
              bin_num += '0';
        }
    }
     
  static void Main() {
    deci_to_bin(1048576);
       
    Console.Write(bin_num);
  }
}
 
// This code is contributed by mukesh07.


Javascript




<script>
    // Javascript program for decimal to binary
    // conversion using recursion
     
    let bin_num = "";
     
    // Function to convert decimal to binary
    function deci_to_bin(x)
    {
 
        // Base Case
        if (x <= 1)
            bin_num += String.fromCharCode(x + '0'.charCodeAt());
        else {
 
            // Recursion call
            deci_to_bin(parseInt(x / 2, 10));
 
            // If x is divisible by 2
            if(x%2 != 0)
              bin_num += '1';
 
            // otherwise
            else
              bin_num += '0';
        }
    }
     
    deci_to_bin(1048576);
      
    document.write(bin_num);
     
    // This code is contributed by divyeshrabadiya07.
</script>


Output

100000000000000000000

Time Complexity: O(log n), where n is given decimal number
Auxiliary Space: O(log n)



Previous Article
Next Article

Similar Reads

Decimal to Binary using recursion and without using power operator
Given an integer N, the task is convert and print the binary equaiva;ent of N.Examples: Input: N = 13 Output: 1101Input: N = 15 Output: 1111 Approach Write a recursive function that takes an argument N and recursively calls itself with the value N / 2 as the new argument and prints N % 2 after the call. The base condition will be when N = 0, simply
3 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Program to convert a Binary Number to Hexa-Decimal Number
Given a Binary Number, the task is to convert this Binary number to its equivalent Hexa-Decimal Number.Examples: Input: 100000101111 Output: 82F Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1111. Here, 1000 is equivalent to 8, 0010 is equivalent to 2 and 1111 is equivalent to F Therefore, the number becomes 82FInput:10101
10 min read
Sum of decimal equivalents of binary node values in each level of a Binary Tree
Given a Binary Tree consisting of nodes with values 0 and 1 only, the task is to find the total sum of the decimal equivalents of the binary numbers formed by connecting nodes at the same level from left to right, on each level. Examples: Input: Below is the given Tree: 0 / \ 1 0 / \ / \ 0 1 1 1Output: 9Explanation: Binary number formed at level 1
15 min read
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965}; Output : 290 530 965 Tree represented is, 890 / \ 325 965 / \ 290 530 Input : preorder[] = { 3, 2, 4 }; Output : 2 4 In this post, a simple recursive sol
5 min read
Find the node with minimum value in a Binary Search Tree using recursion
Given a Binary Search Tree, the task is to find the node with minimum value. Examples: Input: Output: 4 Approach: Just traverse the node from root to left recursively until left is NULL. The node whose left is NULL is the node with the minimum value. Below is the implementation of the above approach: C/C++ Code // C++ implementation of the approach
7 min read
Find the node with maximum value in a Binary Search Tree using recursion
Given a Binary Search Tree, the task is to find the node with maximum value. Examples: Input: Output: 22 Approach: Just traverse the node from root to right recursively until right is NULL. The node whose right is NULL is the node with the maximum value. Below is the implementation of the above approach: C/C++ Code // C++ implementation of the appr
7 min read
Find maximum and minimum element in binary tree without using recursion or stack or queue
Given a binary tree. The task is to find out the maximum and minimum element in a binary tree without using recursion or stack or queue i.e, space complexity should be O(1). Examples: Input : 12 / \ 13 10 / \ 14 15 / \ / \ 21 24 22 23 Output : Max element : 24 Min element : 10 Input : 12 / \ 19 82 / / \ 41 15 95 \ / / \ 2 21 7 16 Output : Max eleme
10 min read
Find Maximum Level Sum in Binary Tree using Recursion
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it and print the maximum sum.Examples: Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 6 Sum of all nodes of the 1st level is 4. Sum of all nodes of the 2nd level is -3. Sum of all nodes of the 3rd level is 6. Hence, the maximum sum is 6. Input: 1 / \ 2
10 min read
Construct a Binary Tree in Level Order using Recursion
Given an array of integers, the task is to construct a binary tree in level order fashion using Recursion. Examples Given an array arr[] = {15, 10, 20, 8, 12, 16, 25} Approach: Idea is to keep track of the number of child nodes in the left sub-tree and right sub-tree and then take the decision on the basis of these counts. When the count of childre
10 min read
three90RightbarBannerImg