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

Decimal to binary number using recursion

Last Updated : 01 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Binary to Gray code using recursion
Given the Binary code of a number as a decimal number, we need to convert this into its equivalent Gray Code. Assume that the binary number is in the range of integers. For the larger value, we can take a binary number as string. In gray code, only one bit is changed in 2 consecutive numbers. Examples: Input: 1001 Output: 1101Explanation: 1001 -
5 min read
Number of substrings with odd decimal value in a binary string
Given a binary string containing only 0's and 1's. Write a program to find number of sub-strings of this string whose decimal representation is odd. Examples : Input : 101 Output : 3 Explanation : Substrings with odd decimal representation are: {1, 1, 101} Input : 1101 Output : 6 Explanation : Substrings with odd decimal representation are: {1, 1,
6 min read
Sum of decimal equivalent of all possible pairs of Binary representation of a Number
Given a number N. The task is to find the sum of the decimal equivalent of all the pairs formed from the binary representation of the given number. Examples: Input: N = 4 Output: 4 Binary equivalent of 4 is 100. All possible pairs are 10, 10, 00 and their decimal equivalent are 2, 2, 0 respectively. So, 2 + 2+ 0 = 4 Input: N = 11 Output: 13 All pos
5 min read
Convert decimal fraction to binary number
Given a fraction decimal number n and integer k, convert decimal number n into equivalent binary number up-to k precision after decimal point. Examples: Input: n = 2.47, k = 5 Output: 10.01111 Input: n = 6.986 k = 8 Output: 110.11111100We strongly recommend that you click here and practice it, before moving on to the solution. A) Convert the integr
9 min read
Decimal to binary conversion without using arithmetic operators
Find the binary equivalent of the given non-negative number n without using arithmetic operators. Examples: Input : n = 10Output : 1010 Input : n = 38Output : 100110 Note that + in below algorithm/program is used for concatenation purpose. Algorithm: decToBin(n) if n == 0 return "0" Declare bin = "" Declare ch while n &gt; 0 if (n &amp; 1) == 0 ch
8 min read
Print ancestors of a given binary tree node without recursion
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Following are different input keys and their ancestors in the above tree Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1
15 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
Count Set-bits of number using Recursion
Given a number N. The task is to find the number of set bits in its binary representation using recursion. Examples: Input : 21 Output : 3 21 represented as 10101 in binary representation Input : 16 Output : 1 16 represented as 10000 in binary representation Approach: First, check the LSB of the number.If the LSB is 1, then we add 1 to our answer a
4 min read
Add the given digit to a number stored in a linked list using recursion
Given a linked list which represents an integer number where each node is a digit of the represented integer. The task is to add a given digit N to the represented integer.Examples: Input: LL = 9 -&gt; 9 -&gt; 3 -&gt; NULL, N = 7 Output: 1 -&gt; 0 -&gt; 0 -&gt; 0 -&gt; NULL 993 + 7 = 1000Input: LL = 2 -&gt; 9 -&gt; 9 -&gt; NULL, N = 5 Output: 3 -
10 min read
Program to find all Factors of a Number using recursion
Given a number N, the task is to print all the factors of N using recursion.Examples: Input: N = 16 Output: 1 2 4 8 16 Explanation: 1, 2, 4, 8, 16 are the factors of 16. A factor is a number which divides the number completely. Input: N = 8 Output: 1 2 4 8 Approach: The idea is to create a function that takes 2 arguments. The function is recursivel
3 min read
Count the occurrence of digit K in a given number N using Recursion
Given an integer N greater than 0, the task is to find the occurrence of digit K present in the given number N. Examples: Input: N = 10000, K = 0 Output: 4 Explanation: Occurrence of '0' digit in 10000 is 4. Input: N = 51435, K = 5 Output: 2 Explanation: Occurrence of '5' digit in 51435 is 2 Approach: The idea is to use recursion to extract the lea
3 min read
Digital Root of a given large number using Recursion
Given a large number num in the form of string with length as N, the task is to find its digital root. The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the
7 min read
How to solve problems related to Number-Digits using Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. A method to solve the number digit problems using recursion is discussed in this article. Two main components exist for any r
4 min read
Sum of digit of a number using recursion
Given a number, we need to find sum of its digits using recursion.Examples:   Input : 12345Output : 15Input : 45632Output :20   The step-by-step process for a better understanding of how the algorithm works. Let the number be 12345. Step 1-&gt; 12345 % 10 which is equal-too 5 + ( send 12345/10 to next step ) Step 2-&gt; 1234 % 10 which is equal-too
4 min read
Given a number N in decimal base, find number of its digits in any base (base b)
Given A Number n in a base 10, find the number of digits in its base b representation. Constraints : [Tex]N \in \mathbb{W} [/Tex]Whole Examples : Input : Number = 48 Base = 4 Output: 3 Explanation : (48)10 = (300)4 Input : Number = 1446 Base = 7 Output: 4 Explanation : (446)10 = (4134)7 A simple approach: convert the decimal number into the given b
8 min read
Program to Convert BCD number into Decimal number
Given a BCD (Binary Coded Decimal) number, the task is to convert the BCD number into its equivalent Decimal number. Examples: Input: BCD = 100000101000 Output: 828 Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1000. Here, 1000 is equivalent to 8 and 0010 is equivalent to 2. So, the number becomes 828. Input: BCD = 1001000
10 min read
Count number of digits after decimal on dividing a number
We are given two numbers A and B. We need to calculate the number of digits after decimal. If in case the numbers are irrational then print "INF".Examples: Input : x = 5, y = 3 Output : INF 5/3 = 1.666.... Input : x = 3, y = 6 Output : 1 3/6 = 0.5 Recommended PracticeCount number of digits after decimalTry It! The idea is simple we follow school di
5 min read
Decimal representation of given binary string is divisible by 20 or not
The problem is to check whether the decimal representation of the given binary number is divisible by 20 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or the minimum numbers of multiplication and division operations. No leadings 0’s are there in the input. Ex
14 min read