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
What is java in simple terms?
Can we use both this () and super () in a constructor?
Explain about method local inner classes or local inner classes in java?
Is there any case when finally will not be executed?
What is a final class in java?
Why stringbuilder is not thread safe in java?
What is the meaning of I ++ in java?
Which language is java?
what are different ways in which a thread can enter the waiting state? : Java thread
Differences between C and Java?
What are instance variables?
What is meant by binding in rmi?
What modifiers are allowed for methods in an interface?
Garbage collection in java?
In multi-threading how can we ensure that a resource isn't used by multiple threads simultaneously?