BCD addition of given Decimal numbers

Given two numnbers A and B, the task is to perform BCD Addition of the given numbers.


Input: A = 12, B = 20
Output: 110010
The summation of A and B is 12 + 20 = 32.
The binary representation of 3 = 0011
The binary representation of 2 = 0010
Therefore, the BCD Addition is “0011” + “0010” = “110010”

Input: A = 10, B = 10
The summation of A and B is 10 + 10 = 20.
The binary representation of 2 = 0010
The binary representation of 0 = 0000
Therefore, the BCD Addition is “0010” + “0000” = “100000”

Approach: The idea is to convert the summation of given two numbers A and B to BCD Number. Below are the steps:

  1. Find the summation(say num) of the two given numbers A and B.
  2. For each digit in the number num, convert it into binary representation upto 4 bits.
  3. Concatenate the binary representation of each digit above and print the result.

Below is the implementation of the above approach:






// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to perform BCD Addition
string BCDAddition(int A, int B)
    // Store the summation of A and B
    // in form of string
    string s = to_string(A + B);
    int l = s.length();
    // To store the final result
    string ans;
    string str;
    // Forming BCD using Bitset
    for (int i = 0; i < l; i++) {
        // Find the binary representation
        // of the current characters
        str = bitset<4>(s[i]).to_string();
    // Stripping off leading zeroes.
    const auto loc1 = ans.find('1');
    // Return string ans
    if (loc1 != string::npos) {
        return ans.substr(loc1);
    return "0";
// Driver Code
int main()
    // Given Numbers
    int A = 12, B = 20;
    // Function Call
    cout << BCDAddition(A, B);
    return 0;




Time Complexity: O(log10(A+B))

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : yashbeersingh42