The Wayback Machine - https://web.archive.org/web/20240917195121/https://www.geeksforgeeks.org/bcd-addition-of-given-decimal-numbers/
Open In App

BCD addition of given Decimal numbers

Last Updated : 07 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Examples: 

Input: A = 12, B = 20 
Output: 110010 
Explanation: 
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 
Output:100000 
Explanation: 
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 up to 4 bits.
  3. Concatenate the binary representation of each digit above and print the result.

Below is the implementation of the above approach:

C++




// 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();
        ans.append(str);
    }
 
    // 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;
}


Java




// Java program for the above approach
class GFG{
     
// Function to perform BCD Addition
static String BCDAddition(int A, int B)
{
     
    // Store the summation of A and B
    // in form of string
    String s = String.valueOf(A + B);
    int l = s.length();
  
    // Forming BCD using Bitset
    String temp[] = { "0000", "0001",
                      "0010", "0011",
                      "0100", "0101",
                      "0110", "0111",
                      "1000", "1001" };
    String ans = "";
      
    for(int i = 0; i < l; i++)
    {
         
        // Find the binary representation
        // of the current characters
        String t = temp[s.charAt(i) - '0'];
        ans = ans + String.valueOf(t);
    }
          
    // Stripping off leading zeroes.
    int loc1 = 0;
    while (loc1 < l && ans.charAt(loc1) != '1')
    {
        loc1++;
    }
  
    // Return string ans
    return ans.substring(loc1);
}
 
// Driver code    
public static void main(String[] args)
{
     
    // Given Numbers
    int A = 12;
    int B = 20;
      
    // Function Call
    System.out.println(BCDAddition(A, B));
}
}
 
// This code is contributed by divyesh072019


Python3




# Python3 program for the above approach
 
# Function to perform BCD Addition
def BCDAddition(A, B):
 
    # Store the summation of A and B
    # in form of string
    s = str(A + B)
    l = len(s)
 
    # Forming BCD using Bitset
    temp = [ "0000", "0001", "0010", "0011", "0100",
             "0101", "0110", "0111", "1000", "1001" ]
    ans = ""
     
    for i in range(l):
 
        # Find the binary representation
        # of the current characters
        t = temp[ord(s[i]) - ord('0')]
        ans = ans + str(t)
         
    # Stripping off leading zeroes.
    loc1 = ans.find('1')
 
    # Return string ans
    return ans[loc1:]
 
# Driver Code
 
# Given Numbers
A = 12
B = 20
 
# Function Call
print(BCDAddition(A, B))
 
# This code is contributed by grand_master


C#




// C# program for the above approach
using System;
class GFG
{
     
    // Function to perform BCD Addition
    static String BCDAddition(int A, int B)
    {
          
        // Store the summation of A and B
        // in form of string
        string s = (A + B).ToString();
        int l = s.Length;
       
        // Forming BCD using Bitset
        string[] temp = { "0000", "0001",
                          "0010", "0011",
                          "0100", "0101",
                          "0110", "0111",
                          "1000", "1001" };
        string ans = "";         
        for(int i = 0; i < l; i++)
        {
              
            // Find the binary representation
            // of the current characters
            string t = temp[s[i] - '0'];
            ans = ans + t.ToString();
        }
               
        // Stripping off leading zeroes.
        int loc1 = 0;
        while (loc1 < l && ans[loc1] != '1')
        {
            loc1++;
        }
       
        // Return string ans
        return ans.Substring(loc1);
    }
 
  // Driver code
  static void Main()
  {
     
    // Given Numbers
    int A = 12;
    int B = 20;
       
    // Function Call
    Console.Write(BCDAddition(A, B));
  }
}
 
// This code is contributed by divyeshrbadiya07.


Javascript




<script>
// Javascript program for the above approach
// Function to perform BCD Addition
function BCDAddition(A, B)
{
     
    // Store the summation of A and B
    // in form of string
    var s = (A + B).toString();
    var l = s.length;
 
    // Forming BCD using Bitset
    temp = [ "0000", "0001",
                    "0010", "0011",
                    "0100", "0101",
                    "0110", "0111",
                    "1000", "1001" ]
    var ans = "";        
    for(var i = 0; i < l; i++)
    {
         
        // Find the binary representation
        // of the current characters
        var t = temp[s[i] - '0'];
        ans = ans + t.toString();
    }
         
    // Stripping off leading zeroes.
    var loc1 = 0;
    while (loc1 < l && ans[loc1] != '1')
    {
        loc1++;
    }
 
    // Return string ans
    return ans.substring(loc1);
}
 
// Driver code
 
// Given Numbers
var A = 12;
var B = 20;
 
// Function Call
document.write(BCDAddition(A, B));
 
// This code is contributed by     rutvik_56.
</script>


Output

110010

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



Similar Reads

Convert a given Decimal number to its BCD representation
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
5 min read
Program to convert Hexa-Decimal Number to its equivalent BCD
Given a HexaDecimal Number N, the task is to convert the number to its equivalent Binary Coded Decimal.Examples: Input: 11F Output: 0001 0001 1111 Explanation: Binary of 1 - 0001 Binary of F - 1111 Thus, Equivalent BCD is 0001 0001 1111Input: A D Output: 1010 1101 Explanation: Binary of A - 1010 Binary of D - 1101 Thus, Equivalent BCD is 1010 1101
10 min read
Program to Convert BCD number into Decimal number
Given a BCD (Binary Coded Decimal) number, the task is to convert the BCD number into its equivalent Decimal number. Examples: Input: BCD = 100000101000 Output: 828 Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1000. Here, 1000 is equivalent to 8 and 0010 is equivalent to 2. So, the number becomes 828. Input: BCD = 1001000
10 min read
BCD or Binary Coded Decimal
Binary Coded Decimal, or BCD, is another process for converting decimal numbers into their binary equivalents. It is a form of binary encoding where each digit in a decimal number is represented in the form of bits.This encoding can be done in either 4-bit or 8-bit (usually 4-bit is preferred).It is a fast and efficient system that converts the dec
3 min read
Convert the given BCD to its equivalent Binary form
Given a BCD (Binary Coded Decimal), the task is to convert this to its equivalent Binary number. Examples: Input: 1001000 Output: 110000 Explanation: Integer value of the given BCD is 48(0100 -&gt; 4, 1000 -&gt; 8). (48)10 = (110000)2 Input: 1001001 Output: 110000 Approach: In order to solve this problem we need to split the given BCD number into b
6 min read
Addition of two numbers without carry
You are given two positive numbers n and m. You have to find a simple addition of both numbers but with a given condition that there is not any carry system in this addition. That is no carry is added at higher MSBs.Examples : Input : m = 456, n = 854 Output : 200 Input : m = 456, n = 4 Output : 450 Algorithm : Input n, m while(n||m) { // Add each
6 min read
Addition of two numbers without propagating Carry
Given 2 numbers a and b of same length. The task is to calculate their sum in such a way that when adding two corresponding positions the carry has to be kept with them only instead of propagating to the left.See the below image for reference: Examples: Input: a = 7752 , b = 8834 Output: 151586 Input: a = 123 , b = 456 Output: 579 Approach: First o
15 min read
Range queries for alternatively addition and subtraction on given Array
Given an array arr[] of N integers and Q queries where every row consists of two numbers L and R which denotes the range [L, R], the task is to find the value of alternate addition and subtraction of the array element between range [L, R]. Examples: Input: arr[] = {10, 13, 15, 2, 45, 31, 22, 3, 27}, Q[][] = {{2, 5}, {6, 8}, {1, 7}, {4, 8}, {0, 5}}
15+ min read
Minimize subset addition or multiplication to make two given triplets equal
Given three integers A, B, C denoting a triplet and three integers P, Q, R denoting another triplet. Repeatedly select any integer and add or multiply it to all elements in a subset (A, B, C) with that integer until the two given triplets become equal. The task is to find the minimum number of such operations required to make the two triplets equal
14 min read
Find minimum value expression by inserting addition or multiplication operator between digits of given number
Given string str that contains only digits, the task is to return an expression by inserting the '+' or '*' operator between every two digits such that the arithmetic value of the expression is minimized. Example: Input: str = "322"Output: "3+2*2"Explanation: The value of above expression is 7 which is minimum possible over the other expressions "3
6 min read
Number of decimal numbers of length k, that are strict monotone
We call a decimal number strict monotone if: D[i-1] &lt; D[i], 0 &lt; i &lt; |D| Write a program which takes positive number n on input and returns number of decimal numbers of length n that are strict monotone. Number can't start with 0. Examples : Input : 2 Output : 36 Numbers are 12, 13, ... 19, 23 24, ... 29, .... 89. Input : 3 Output : 84 Expl
5 min read
Number of digits before the decimal point in the division of two numbers
Given two integers a and b. The task is to find the number of digits before the decimal point in a / b.Examples: Input: a = 100, b = 4 Output: 2 100 / 4 = 25 and number of digits in 25 = 2.Input: a = 100000, b = 10 Output: 5 Naive approach: Divide the two numbers and then find the number of digits in the division. Take the absolute value of the div
6 min read
Queries to count numbers from a range which does not contain digit K in their decimal or octal representation
Given an integer K and an array Q[][] consisting of N queries of type {L, R}, the task for each query is to print the count of numbers from the range [L, R] that doesn't contain the digit K in their decimal representation or octal representation. Examples: Input: K = 7, Q[][] = {{1, 15}}Output: 13Explanation:Only number 7 and 15 contains digit K in
9 min read
Karatsuba Algorithm for fast Multiplication of Large Decimal Numbers represented as Strings
Given two numeric strings A and B, the task is to find the product of the two numeric strings efficiently. Example: Input: A = 5678, B = 1234Output: 7006652 Input: A = 74638463789, B = 35284567382Output: 2633585904851937530398 Approach: The given problem can be solved using Karastuba's Algorithm for Fast Multiplication, the idea is to append zeroes
15+ min read
Bitwise recursive addition of two integers
When adding two binary numbers by hand we keep the carry bits in mind and add it at the same time. But to do same thing in program we need a lot of checks. Recursive solution can be imagined as addition of carry and a^b (two inputs) until carry becomes 0. Examples : Input : int x = 45, y = 45 Output : 90 Input : int x = 4, y = 78 Output : 82 Sum of
4 min read
Minimum steps in which N can be obtained using addition or subtraction at every step
Given N, print the sequence of a minimum number of steps in which N can be obtained starting from 0 using addition or subtraction of the step number. Note: At each step, we can add or subtract a number equal to the step number from the current position. For example, at step 1 we can add 1 or -1. Similarly, at step 2 we add 2 or -2 and so on. The be
11 min read
Add N digits to A such that it is divisible by B after each addition
Given three integers A, B and N, repeat the following process N times: Add a digit to A such that after adding it, A is divisible by B.Print the smallest value of A possible after N iterations of above operation.Print -1 if the operation fails. Note : We need to check divisibility after every digit addition.Examples: Input: A = 10, B = 11, N = 1 Ou
5 min read
Find the maximum component size after addition of each edge to the graph
Given an array arr[][] which contains the edges of a graph to be used to construct an undirected graph G with N nodes, the task is to find the maximum component size in the graph after each edge is added while constructing the graph. Examples: Input: N = 4, arr[][] = {{1, 2}, {3, 4}, {2, 3}} Output: 2 2 4 Explanation: Initially, the graph has 4 ind
15+ min read
Modify array by merging elements with addition such that it consists of only Primes.
Given an array arr[] consisting of positive integers, the task is to check whether we can modify the array by adding any of the elements of the array such that it consists of only Primes. Examples: Input: arr[] = {3, 5, 7, 21} Output: YES Explanation: Add the following elements, 3+5+21 So the array becomes {7, 29} which consists of only primes. Inp
10 min read
Number formed after K times repeated addition of smallest divisor of N
Given two integers N and K, the task is to generate the final outcome of performing K operations which involves adding the smallest divisor, other than 1, of the current value of N to it at every step.Example: Input: N = 9, K = 4 Output: 18 Explanation: Divisors of 9 are {1, 3, 9} 1st Operation: N = 9 + 3 = 12 2nd Operation: N = 12 + 2 = 14 3rd Ope
5 min read
Maximize occurrences of values between L and R on sequential addition of Array elements with modulo H
Given an array arr[] having N positive integers and a positive integers H, the task is to count the maximum occurrences of a value from the range [L, R] on adding arr[i] or arr[i] - 1 to X (initially 0). The integer X must be always be less than H. If it is greater than H, replace X by X % H Examples: Input: arr = {16, 17, 14, 20, 20, 11, 22}, H =
15 min read
Minimum addition/removal of characters to be done to make frequency of each character prime
Given a string S of length N, the task is to find the minimum operations required to make the frequency of every distinct character prime. The frequency of a character can be increased or decreased by 1 in a single operation. Examples: Input: S = "abba" Output: 0 Explanation: There are two characters in the string S and the frequency of 'a' is 2 wh
14 min read
Maximize median after doing K addition operation on the Array
Given an array arr[] of N elements and an integer K, the task is to perform at most K operation on the array. In the one operation increment any element by one of the array. Find maximize median after doing K such operation. Example: Input: arr[] = {1, 3, 4, 5}, K = 3Output: 5Explanation: Here we add two in the second element and one in the third e
9 min read
Minimum repeated addition of even divisors of N required to convert N to M
Given two numbers N and M, the task is to find the minimum operations required to convert N to M by repeatedly adding it with all even divisors of N except N. Print -1 if the conversion is not possible. Examples: Input: N = 6, M = 24Output: 4Explanation:Step1: Add 2 (2 is an even divisor and 2!= 6) to 6. Now N becomes 8.Step2: Add 4 (4 is an even d
15+ min read
Sum of all possible expressions of a numeric string possible by inserting addition operators
Given a numeric string str of length N, the task is to find the sum of all possible expressions by inserting the '+' operator between the characters of the string any number of times. Examples: Input: str = "125" Output: 176 Explanation: Inserting "+" after 1st index modifies str to "1+25" and value = 26 Inserting "+" after 2nd index modifies str t
8 min read
Minimum moves to make M and N equal by repeated addition of divisors except 1 using Dynamic Programming
Given two integers N and M, the task is to calculate the minimum number of moves to change N to M, where In one move it is allowed to add any divisor of the current value of N to N itself except 1. Print "-1" if it is not possible. Example: Input: N = 4, M = 24Output: 5Explanation: The given value of N can be converted into M using the following st
8 min read
Maximizing Subarray sum with constrained traversal and addition time
Given two integers N and M representing the Length of arr[] and number of seconds. The task is to maximize the sum of the subarray where it takes 0.5secs to travel in consecutive elements and 0.5secs to add a value of the element in sum. It is given that one can start from any element. Example: Input: N = 7, M = 3, arr[] = { 2, 1, 3, 5, 0, 1, 4 }Ou
6 min read
Split N into two integers whose addition to A and B makes them equal
Given three positive integers A, B and N, the task is to split N into two parts such that they become equal i.e. find two positive integers X and Y, such that X + Y = N and A + X = B + Y. If no such pair exists, print -1. Examples: Input: A = 1, B = 3, N = 4 Output: 3 1 Explanation: If X = 3 and Y = 1, then A + X = B + Y and X + Y =4 Input: A = 1,
8 min read
Program for addition of two matrices
Given two N x M matrices. Find a N x M matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: Below is the idea to solve the problem. Iterate over every cell of matrix (i, j), add the corres
7 min read
Convert Array a[] to b[] through Subsequence addition
Given an array a[] equal = {1} and a target array b[], the task is to check whether you can transform a to b or not by performing an operation on array a[]. The operation is defined as choosing any subsequence of array a and insert the sum of the numbers of the subsequence to the array a at any position. Examples: Input: b[] = {5, 1, 3, 2, 1}Output
6 min read