Showing posts with label Sum two numbers without arithmetic operator. Show all posts
Showing posts with label Sum two numbers without arithmetic operator. Show all posts

Sunday, 26 September 2021

Sum two number without arithmetic operator

Sum two number without arithmetic operator, Using C#


using System; 

namespace ConsoleApp1

{

    public class Program

    {

        static void Main()

        {

            int sum = SumWithoutArithmeticOprator(25, 7);

            Console.WriteLine($"Sum of two numbers is {sum}");

            Console.ReadLine();

        }

 

        private static int SumWithoutArithmeticOprator(int v1, int v2)

        {

            if (v2 == 0) return v1;

            if (v1 == 0) return v2;

            // Where v1 ^ v2: XOR bitwise calculation

            // v1 & v2: AND bitwise with carry

            return SumWithoutArithmeticOprator((v1 ^ v2), (v1 & v2) << 1);

        }

    }

}