Add Two Numbers With Bitwise Operator

In this post you will learn to add two numbers with bitwise operator.

Since we are not using arithmetic operators in the below example, add_Two_Numbers function is used. The following program demonstrates the example,

Example: Add Two Numbers With Bitwise Operator

Also Read РAddition Program in Java

import java.util.Scanner;

public class Bitwise_Addition {

static int add_Two_Numbers(int a,int b){
int carry_carry_Num;

while(b ! =  0){
carry_Num = a & b;
a = a ^ b;
b = carry_Num << 1;
}
return a;
}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Please enter numbers to be added: ");

int a = sc.nextInt(); // Scans the next token of the input as an int.
int b = sc.nextInt(); // Scans the next token of the input as an int.

System.out.println("The output is: " + add_Two_Numbers(a,b));
sc.close();
}
}

Output:

Add Two Numbers With Bitwise Operator

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *