Open In App

Add two unsigned numbers using bits

Improve
Improve
Like Article
Like
Save
Share
Report

Given two unsigned integers (maximum possible input can be of 32 bits). The task is to add two numbers using bit operations. 

Examples:  

Input: n1 = 12, n2 = 34
Output: 46
Input: n1 = 12564 n2 = -1
Output: 12563

Approach: Since we know that in bit addition  

  • 1+0=1
  • 0+1=1
  • 0+0=0
  • 1+1=0 carry 1
  • if(carry==1) 1+1=1 carry 1


Represent integer using bitset function in C++ . It behaves like an array which stores the LSB (Least Significant Bit) at 0th index and when we print such an array it prints the binary representation in reverse format. Add every bit from right according to the bits addition property and store in the third bitset. Function to_ulong() is used to convert a bitset form into its decimal form.
Below is the implementation of the above approach. 
 

C++
#include <bits/stdc++.h>
#define M 32
using namespace std;

// Function to add two bitset
int binAdd(bitset<M> atemp, bitset<M> btemp)
{
    // To store the bits of answer
    bitset<M> ctemp;
    for (int i = 0; i < M; i++)
        ctemp[i] = 0;

    // Initialize carry to 0
    int carry = 0;

    for (int i = 0; i < M; i++) {

        // Both bits are zero
        if (atemp[i] + btemp[i] == 0) {

            if (carry == 0)
                ctemp[i] = 0;

            else {
                ctemp[i] = 1;
                carry = 0;
            }
        }

        // Any of the one bit is 1
        else if (atemp[i] + btemp[i] == 1) {

            if (carry == 0)
                ctemp[i] = 1;
            else {
                ctemp[i] = 0;
            }
        }

        // Both bits are 1
        else {
            if (carry == 0) {
                ctemp[i] = 0;
                carry = 1;
            }
            else {
                ctemp[i] = 1;
            }
        }
    }

    // To convert bitset into
    // decimal equivalent
    return ctemp.to_ulong();
}

// Driver Code
int main()
{
    int number1, number2;
    number1 = 12;
    number2 = 34;

    // Converting number 1 to bitset form
    bitset<M> num1(number1);

    // Converting number 2 to bitset form
    bitset<M> num2(number2);

    cout << binAdd(num1, num2) << endl;
}
Java
// Java program to add two unsigned numbers using bits

import java.util.*; // Needed for BitSet class.

class GFG {
    static final int M = 32;

    // Function to add two BitSets. Returns long number.
    static long binAdd(BitSet atemp, BitSet btemp)
    {
        // Initialize a 3rd BitSet to store the answer.
        BitSet ctemp = new BitSet(M);
        for (int i = 0; i < M; i++) {
            ctemp.set(i, false);
        }

        // Initialize carry to ZERO.
        int carry = 0;

        for (int i = 0; i < M; i++) {

            // Both of the bits are ZERO.
            if (atemp.get(i) == false
                && // Uses the "conditional-AND" operator
                   // (also known as "short-circuit AND")
                   // which is more efficient than the
                   // ordinary & bitwise operator.
                btemp.get(i) == false) {

                if (carry == 0) {
                    ctemp.set(i, false);
                }
                else {
                    ctemp.set(i, true);
                    carry = 0;
                }
            }

            // Either of the bits is a ONE but not both.
            else if (atemp.get(i) == true
                     ^ // Uses the "XOR" (exclusive-OR)
                       // operator to ensure that ONLY
                       // one of the two bits is a ONE.
                     btemp.get(i) == true) {

                if (carry == 0) {
                    ctemp.set(i, true);
                }
                else {
                    ctemp.set(i, false);
                }
            }

            // Both of the bits are ONE.
            else // By process of elimination we do not need
                 // to code for the (TRUE & TRUE) condition.
            {
                if (carry == 0) {
                    ctemp.set(i, false);
                    carry = 1;
                }
                else {
                    ctemp.set(i, true);
                }
            }
        }

        // Returns the 3rd BitSet as its decimal equivalent
        // number in long format.
        return ctemp.toLongArray()[0];
    }

    // Driver Code
    public static void main(String args[])
    {
        int number1, number2;

        // binary literal for decimal 15.
        number1 = 15;
        // binary literal for decimal 85.
        number2 = 1;
        // result should be decimal 100.

        // Converting number1 to BitSet form.
        BitSet num1
            = BitSet.valueOf(new long[] { number1 });

        // Converting number2 to BitSet form.
        BitSet num2
            = BitSet.valueOf(new long[] { number2 });

        System.out.printf("%d plus %d equals %d", number1,
                          number2, binAdd(num1, num2));
        System.out.println();
    }
}

// This code is contributed by Arnab Kundu.
// Modified by Matt Ambrose.
C#
using System;
using System.Collections;

class Program
{
    const int M = 32;

    // Function to add two bitsets
    static int BinAdd(BitArray atemp, BitArray btemp)
    {
        // To store the bits of answer
        BitArray ctemp = new BitArray(M);

        // Initialize carry to 0
        int carry = 0;

        for (int i = 0; i < M; i++)
        {
            // Both bits are zero
            if (Convert.ToInt32(atemp[i]) + Convert.ToInt32(btemp[i]) == 0)
            {
                if (carry == 0)
                    ctemp[i] = false;
                else
                {
                    ctemp[i] = true;
                    carry = 0;
                }
            }

            // Any of the one bit is 1
            else if (Convert.ToInt32(atemp[i]) + Convert.ToInt32(btemp[i]) == 1)
            {
                if (carry == 0)
                    ctemp[i] = true;
                else
                    ctemp[i] = false;
            }

            // Both bits are 1
            else
            {
                if (carry == 0)
                {
                    ctemp[i] = false;
                    carry = 1;
                }
                else
                    ctemp[i] = true;
            }
        }

        // To convert bitset into decimal equivalent
        return BinToInt(ctemp);
    }

    // Function to convert bitset into integer
    static int BinToInt(BitArray bitArray)
    {
        int[] array = new int[1];
        bitArray.CopyTo(array, 0);
        return array[0];
    }

    // Driver Code
    static void Main(string[] args)
    {
        int number1 = 12;
        int number2 = 34;

        // Converting number 1 to bitset form
        BitArray num1 = new BitArray(new int[] { number1 });

        // Converting number 2 to bitset form
        BitArray num2 = new BitArray(new int[] { number2 });

        Console.WriteLine(BinAdd(num1, num2));
    }
}
Javascript
// Function to convert given Integer
// to list of bits of length M
function bitset(num) {
    return num.toString(2).padStart(32, '0').split('').map(Number);
}

// Function to add two bitsets
function binAdd(atemp, btemp) {
    // To store the bits of the answer
    let ctemp = Array(32).fill(0);

    // Initialize carry to 0
    let carry = 0;

    for (let i = 0; i < 32; i++) {
        // Both bits are zero
        if (atemp[i] + btemp[i] === 0) {
            if (carry === 0) {
                ctemp[i] = 0;
            } else {
                ctemp[i] = 1;
                carry = 0;
            }
        }
        // Any of the one bit is 1
        else if (atemp[i] + btemp[i] === 1) {
            if (carry === 0) {
                ctemp[i] = 1;
            } else {
                ctemp[i] = 0;
            }
        }
        // Both bits are 1
        else {
            if (carry === 0) {
                ctemp[i] = 0;
                carry = 1;
            } else {
                ctemp[i] = 1;
            }
        }
    }

    // Convert bitset into string and then
    // convert string to its decimal equivalent
    let temp = ctemp.join('');
    return parseInt(temp, 2);
}

// Driver Code
let number1 = 12;
let number2 = 34;
let M = 32;

// Converting number 1 to bitset form
let num1 = bitset(number1);

// Converting number 2 to bitset form
let num2 = bitset(number2);

console.log(binAdd(num1, num2));
//this code is contributed by prachi
Python3
# Python3 implementation of the approach

# Function to convert given Integer
# to list of bits of length M
def bitset(num):
    
    return [int(x) for x in format(num, '032b')]
    
# Function to add two bitset 
def binAdd(atemp, btemp): 

    # To store the bits of answer 
    ctemp = [0] * M 
    
    # Initialize carry to 0 
    carry = 0
    for i in range(0, M): 

        # Both bits are zero 
        if atemp[i] + btemp[i] == 0: 

            if carry == 0:
                ctemp[i] = 0

            else: 
                ctemp[i] = 1
                carry = 0
            
        # Any of the one bit is 1 
        elif atemp[i] + btemp[i] == 1: 

            if carry == 0:
                ctemp[i] = 1
            else: 
                ctemp[i] = 0

        # Both bits are 1 
        else:
            if carry == 0: 
                ctemp[i] = 0
                carry = 1
            
            else:
                ctemp[i] = 1
            
    # To convert bitset into string and then 
    # convert string to its decimal equivalent 
    temp = ''.join([str(x) for x in ctemp])
    return int(temp, 2)
    
# Driver Code 
if __name__ == "__main__": 

    number1, number2 = 12, 34
    M = 32
    
    # Converting number 1 to bitset form 
    num1 = bitset(number1) 

    # Converting number 2 to bitset form 
    num2 = bitset(number2) 

    print(binAdd(num1, num2))
    
# This code is contributed by Rituraj Jain

Output
46


Last Updated : 18 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads