📜  使用递归且不使用幂运算符的十进制到二进制

📅  最后修改于: 2021-05-04 14:34:14             🧑  作者: Mango

给定整数N ,任务将被转换并打印N的二进制等式。

例子:

方法编写一个递归函数,该递归函数接受参数N并以值N / 2作为新参数递归调用自身,并在调用后输出N%2 。基本条件是N = 0时,仅打印0并在这种情况下返回该函数。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Recursive function to convert n
// to its binary equivalent
void decimalToBinary(int n)
{
    // Base case
    if (n == 0) {
        cout << "0";
        return;
    }
  
    // Recursive call
    decimalToBinary(n / 2);
    cout << n % 2;
}
  
// Driver code
int main()
{
    int n = 13;
  
    decimalToBinary(n);
  
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
  
class GFG
{
      
  
// Recursive function to convert n
// to its binary equivalent
static void decimalToBinary(int n)
{
    // Base case
    if (n == 0) 
    {
        System.out.print("0");
        return;
    }
  
    // Recursive call
    decimalToBinary(n / 2);
    System.out.print( n % 2);
}
  
// Driver code
public static void main (String[] args) 
{
    int n = 13;
  
    decimalToBinary(n);
}
}
  
// This code is contributed by anuj_67..


Python3
# Python3 implementation of the approach 
  
# Recursive function to convert n 
# to its binary equivalent 
def decimalToBinary(n) :
      
    # Base case 
    if (n == 0) :
        print("0",end=""); 
        return;
      
    # Recursive call 
    decimalToBinary(n // 2); 
    print(n % 2,end=""); 
  
  
# Driver code 
if __name__ == "__main__" : 
  
    n = 13;
    decimalToBinary(n); 
      
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
      
class GFG
{
      
    // Recursive function to convert n
    // to its binary equivalent
    static void decimalToBinary(int n)
    {
          
        // Base case
        if (n == 0) 
        {
            Console.Write("0");
            return;
        }
  
        // Recursive call
        decimalToBinary(n / 2);
        Console.Write(n % 2);
    }
  
    // Driver code
    public static void Main(String[] args) 
    {
        int n = 13;
  
        decimalToBinary(n);
    }
}
  
// This code is contributed by 29AjayKumar


输出:
01101