Número decimal a binario usando recursividad

Dado un número decimal como entrada, necesitamos escribir un programa para convertir el número decimal dado en un número binario equivalente. 

Ejemplos: 

Input : 7                                                         
Output :111

Input :10
Output :1010

Hemos discutido una solución iterativa en la publicación a continuación. 
Programa para la conversión de decimal a binario
A continuación se muestra la solución recursiva:

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

Proceso paso a paso para una mejor comprensión de cómo funciona el algoritmo 
Deje que el número decimal sea 10. 
Paso 1-> 10 % 2 que es igual a 0 + 10 * ( 10/2 ) % 2 
Paso 2-> 5 % 2 que es igual-demasiado 1 + 10 * ( 5 / 2 ) % 2
Paso 3-> 2 % 2 que es igual-demasiado 0 + 10 * ( 2 / 2 ) % 2
Paso 4-> 1 % 2 que es igual-demasiado 1 + 10 * ( 1 / 2 ) % 2

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>
Producción

1010

El enfoque anterior funciona bien a menos que desee convertir un número mayor que 1023 en decimal a binario. El binario de 1024 es 10000000000 (un 1 y diez 0) que sale del rango de int. Incluso con long long unsigned como tipo de devolución, lo más alto que puede alcanzar es 1048575, que es mucho menor que el rango de int. Un enfoque más fácil pero efectivo sería almacenar los dígitos individuales del número binario en un vector de 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>
Producción

100000000000000000000

Publicación traducida automáticamente

Artículo escrito por Shahnawaz_Ali y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *