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 print 0 and return out of the function in that case. Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void decimalToBinary(int n)
{
if (n == 0) {
cout << "0";
return;
}
decimalToBinary(n / 2);
cout << n % 2;
}
int main()
{
int n = 13;
decimalToBinary(n);
return 0;
}
Java
import java.io.*;
class GFG
{
static void decimalToBinary(int n)
{
if (n == 0)
{
System.out.print("0");
return;
}
decimalToBinary(n / 2);
System.out.print( n % 2);
}
public static void main (String[] args)
{
int n = 13;
decimalToBinary(n);
}
}
Python3
def decimalToBinary(n) :
if (n == 0) :
print("0",end="");
return;
decimalToBinary(n // 2);
print(n % 2,end="");
if __name__ == "__main__" :
n = 13;
decimalToBinary(n);
C#
using System;
class GFG
{
static void decimalToBinary(int n)
{
if (n == 0)
{
Console.Write("0");
return;
}
decimalToBinary(n / 2);
Console.Write(n % 2);
}
public static void Main(String[] args)
{
int n = 13;
decimalToBinary(n);
}
}
Javascript
<script>
function decimalToBinary(n) {
if (n == 0) {
document.write("0");
return;
}
decimalToBinary(parseInt(n / 2));
document.write(n % 2);
}
var n = 13;
decimalToBinary(n);
</script>
Time Complexity: O(logN)Auxiliary Space: O(logN)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule. Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
04 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...