How to add two numbers with out using Arithmetic , union
operators in java....?
But we can use bitwise operators... but how...?
Answer Posted / mathi
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 ? | 1 Yes | 0 No |
Post New Answer View All Answers
Explain importance of finally block in java?
Can a class have a static inner class?
Can we extend singleton class in java?
How does regex work?
How to change the priority of thread or how to set the priority of thread?
What are loops in java?
What is a parameter used for?
How strings are created in java?
How to connect to a remote database using Applet?
What are keyboard events?
How would you dynamically allocate memory to an array?
How do you add spaces in java?
How does sublist works in java?
In which language java is written?
What is the this keyword?