Convert a given Decimal number to its BCD representation
Last Updated :
10 Oct, 2023
Given a decimal number N, the task is to convert N to it’s Binary Coded Decimal(BCD) form.
Examples:
Input: N = 12
Output: 0001 0010
Explanation:
Considering 4-bit concept:
1 in binary is 0001 and 2 in binary is 0010.
So it’s equivalent BCD is 0001 0010.
Input: N = 10
Output: 0001 0000
Explanation:
Considering 4-bit concept:
1 in binary is 0001 and 0 in binary is 0000.
So it’s equivalent BCD is 0001 0000.
Approach:
- Reverse the digits of the given number N using the approach discussed in this article and stored the number in Rev.
- Extract the digits of Rev and print the Binary form of the digit using bitset.
- Repeat the above steps for each digit in Rev.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void BCDConversion( int n)
{
if (n == 0) {
cout << "0000" ;
return ;
}
int rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
while (rev > 0) {
bitset<4> b(rev % 10);
cout << b << ' ' ;
rev /= 10;
}
}
int main()
{
int N = 12;
BCDConversion(N);
return 0;
}
|
Java
import java.util.*;
class Gfg
{
public static void BCDConversion( int n)
{
if (n == 0 )
{
System.out.print( "0000" );
}
int rev = 0 ;
while (n > 0 )
{
rev = rev * 10 + (n % 10 );
n /= 10 ;
}
while (rev > 0 )
{
String b = Integer.toBinaryString(rev % 10 );
b = String.format( "%04d" , Integer.parseInt(b));
System.out.print(b + " " );
rev /= 10 ;
}
}
public static void main(String []args)
{
int N = 12 ;
BCDConversion(N);
}
}
|
Python3
def BCDConversion(n) :
if (n = = 0 ) :
print ( "0000" )
return
rev = 0
while (n > 0 ) :
rev = rev * 10 + (n % 10 )
n = n / / 10
while (rev > 0 ) :
b = str (rev % 10 )
print ( "{0:04b}" . format ( int (b, 16 )), end = " " )
rev = rev / / 10
N = 12
BCDConversion(N)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void BCDConversion( int n)
{
if (n == 0) {
Console.Write( "0000" );
return ;
}
int rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
while (rev > 0) {
string b = Convert.ToString(rev % 10, 2).PadLeft(4, '0' );
Console.Write(b + " " );
rev /= 10;
}
}
static void Main() {
int N = 12;
BCDConversion(N);
}
}
|
Javascript
<script>
function BCDConversion(n)
{
if (n == 0) {
document.write( "0000" );
return ;
}
let rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n = parseInt(n / 10, 10);
}
while (rev > 0) {
let b = (rev % 10).toString(2);
while (b.length != 4)
{
b = "0" + b;
}
document.write(b + " " );
rev = parseInt(rev / 10, 10);
}
}
let N = 12;
BCDConversion(N);
</script>
|
Time Complexity: O(log10 N), where N is the given number.
Auxiliary Space: O(1) because constant space has been used
Share your thoughts in the comments
Please Login to comment...