How to add two numbers with out using Arithmetic , union
operators in java....?

But we can use bitwise operators... but how...?

Answer Posted / sejal

public class BitWiseOpsExample {

public static int add(int x, int y) {

int xor, and, temp;
and = x & y; /* Obtain the carry bits */
xor = x ^ y; /* resulting bits */

while(and != 0 ) /* stop when carry bits are gone */
{
and <<= 1; /* shifting the carry bits one space */
temp = xor ^ and; /* hold the new xor result bits*/
and &= xor; /* clear the previous carry bits and assign the
new carry bits */
xor = temp; /* resulting bits */
}
return xor; /* final result */
}


public static void main(String[] args) {
System.out.println("Add 4 + 7");
System.out.println(add(4,7));

System.out.println("Add 25 + 25");
System.out.println(add(25,25));

}

}

Is This Answer Correct ?    15 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is java in simple terms?

749


Can we use both this () and super () in a constructor?

765


Explain about method local inner classes or local inner classes in java?

769


Is there any case when finally will not be executed?

707


What is a final class in java?

759


Why stringbuilder is not thread safe in java?

778


What is the meaning of I ++ in java?

836


Which language is java?

742


what are different ways in which a thread can enter the waiting state? : Java thread

697


Differences between C and Java?

825


What are instance variables?

805


What is meant by binding in rmi?

750


What modifiers are allowed for methods in an interface?

865


Garbage collection in java?

775


In multi-threading how can we ensure that a resource isn't used by multiple threads simultaneously?

1074