package com.kkjavatutorials.client;

import java.util.Scanner;

/**

* @author KK JavaTutorials

*Java program to add two numbers without using arithmetic operators

*/

public class SumOfTwoNumbersTest {

public static void main(String[] args) {

Scanner scanner = null;

int number1;

int number2;

try {

scanner = new Scanner(System.in);

System.out.print("Enter first number:");

number1 = scanner.nextInt();

System.out.print("Enter second number:");

number2 = scanner.nextInt();

int sumOfTwoNumbers = addTwoNumbers(number1,number2);

System.out.println("Sum of two numbers = "+sumOfTwoNumbers);

} catch (Exception e) {

e.printStackTrace();

}

}

private static int addTwoNumbers(int number1, int number2)

{

// Iterate till there is no carry remain

while (number2 != 0)

{

//Here carry will contain common

//set of bits of number1 and number2

int carry = number1 & number2;

// Now sum of bits of number1 and number2 where at

//least one of the bits is not set

number1 = number1 ^ number2;

//Carry is shifted by one bit so that adding

//it to number1 gives the required sum

number2 = carry << 1;

}

return number1;

}

}