Friday, 21 October 2016

Program to add two numbers without using Arithmetic Operators in Java

Addition of two numbers is very simple but if we have to add two numbers without using Arithmetic operators, then it might be problem for us. But luckily its very simple. For adding two numbers we can use Bitwise Operators instead of Arithmetic Operators.

Here we have implemented Addition of two numbers using Recursion as well as Non-recursion. 

Let us see the program -

package com.anjan.test;

public class Addition {
//Non-recursive implementation of Addition
public int addNonRecur(int a, int b){
while(b !=0){
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
//Recursive implementation of Addition
public int addRecur(int a, int b){
if(b == 0){
return a;
}else{
return addRecur(a ^ b, (a & b) << 1);
}
}
public static void main(String args[]){
Addition a = new Addition();
System.out.println(a.addNonRecur(2, 4));
System.out.println(a.addRecur(6, 4));
}

}


Output -


6
10

No comments:

Post a Comment