As you know to find sum of to two numbers we usually use arithmetic operator(+) but in this post we will write a java program to Adding two numbers without using arithmetic operators.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
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; } } |
Sample output of above program:
1 2 3 |
Enter first number:10 Enter second number:15 Sum of two numbers = 25 |
You may also like:
How to convert number to words in java
How to swap two numbers with or without temporary variable in java
Java Program to Swap two numbers using Bitwise XOR Operator?
How to reverse a number in Java
How to check Armstrong number java program
Java program to find factorial of a number
Java Program to Calculate the Power of a Number
Check whether a number is prime or not
Java Program to displaying prime numbers
Thanks for visiting blog. If you have any doubts or any suggestions to make please drop a comment.