Thursday, January 7, 2021

Add two integers without using arithmetic operators

Problem: Calculate the sum of two integers a and b, but you are not allowed to use any arithmetic operators like  +, ++, - and -- etc.

Example: 

Input: a = -6, b = 4
Output: -2


Approach: We can use the Half Adder logic here.


Implementation in C#:

        public int GetSum(int a, int b)

        {

            while (b != 0)

            {

                int carry = a & b;

                a = a ^ b;

                b = carry << 1;

            }

            return a;

        }


Complexity: O(n) where n is number of bits in integer

No comments:

Post a Comment