Java code :
output :
9
-1
-9
1
5
Explanation : When you add two one-bit quantities, you get a two-bit
result : 0 + 0 = 00, 0 + 1 = 01, 1 + 0 = 01, and 1 + 1 = 10.
Note that the leftmost bit of sum of the the single-bit quantities A
and B, obeys the logic A & B, and the rightmost bit obeys A ^ B, where
& is the logical AND operation and ^ is the logical eXclusive OR
operation. When adding a multibit binary number, the leftmost bit
carries into the next bit position. So the code you presented just
does the multibit addition using the above two rules on all bits in
parallel. The first two statements determine the results using the
"leftmost bit" and "rightmost bit" rules above. If there are any
carries, then they must be added to the next position to the left.
Thus, shift the carries left one bit and repeat the addition process
using the leftmost and rightmost bit rules again. Do this until there
are no remaining carries.
Difference of two numbers :
How to do subtraction of two integers widout using subtractn??
The negative integer can be represented in 2's complement format.So sub_result=a+(~b+1) will perform the subtraction of a and b.
-b=(~b+1).
Refer : http://www.geeksforgeeks.org/archives/18324
public class AddTwoNumbers {
private static int myAdd(int a, int b)
{
int carry = a & b;
int result = a ^ b;
while(carry != 0)
{
int shiftedcarry = carry << 1;
carry = result & shiftedcarry;
result ^= shiftedcarry;
}
return result;
}
public static void main(String[] args){
System.out.println(myAdd(4, 5));
System.out.println(myAdd(4, -5));
System.out.println(myAdd(-4, -5));
System.out.println(myAdd(-4, 5));
System.out.println(myAdd(0, 5));
}
}
output :
9
-1
-9
1
5
Explanation : When you add two one-bit quantities, you get a two-bit
result : 0 + 0 = 00, 0 + 1 = 01, 1 + 0 = 01, and 1 + 1 = 10.
Note that the leftmost bit of sum of the the single-bit quantities A
and B, obeys the logic A & B, and the rightmost bit obeys A ^ B, where
& is the logical AND operation and ^ is the logical eXclusive OR
operation. When adding a multibit binary number, the leftmost bit
carries into the next bit position. So the code you presented just
does the multibit addition using the above two rules on all bits in
parallel. The first two statements determine the results using the
"leftmost bit" and "rightmost bit" rules above. If there are any
carries, then they must be added to the next position to the left.
Thus, shift the carries left one bit and repeat the addition process
using the leftmost and rightmost bit rules again. Do this until there
are no remaining carries.
Difference of two numbers :
How to do subtraction of two integers widout using subtractn??
The negative integer can be represented in 2's complement format.So sub_result=a+(~b+1) will perform the subtraction of a and b.
-b=(~b+1).
Refer : http://www.geeksforgeeks.org/archives/18324
No comments:
Post a Comment