## Find sum of two numbers using only bitwise operators: Add two positive numbers without using + or ++
Problem:SolutionIf bits in both numbers were at different places, then sum is given just by (a | b) If some bits are common in the two numbers, then ORing those will give back those same bits where as a sum operation would have demanded a carry for each such OR between sum bits. These means that bits common in both the numbers need to be handled specially. Bits common in two numbers are given by (a & b)
So A+B = A^B except for last case, where its equal to (A|B << 1) || (A^B) We get the uncommon bits using XOR and common bits using AND Since result of adding common bits is same as multiplying by 2, (Example: 01001 + 01001 = 10010), we just shift the common bits by 1 and add them to uncommon bits recursively. public class AddingWithBitwiseOps { public static void main(String[] args) { int i = (int)(Math.random()*16); int j = (int)(Math.random()*16); System.out.println(add (i, j)); } static int add(int i, int j) { // Debug code printBinary(i); printBinary(j); System.out.println(); // Actual algorithm int uncommonBitsFromBoth = i ^ j; int commonBitsFromBoth = i & j; if (commonBitsFromBoth == 0) return uncommonBitsFromBoth; return add ( uncommonBitsFromBoth, commonBitsFromBoth << 1 ); } static void printBinary(int num) { int n = num; String s = ""; for (int i=0; i<8;i++) { s = (n&1) + s; n = n >gt;>gt; 1; } System.out.println(num + " = " + s); } } :Examples6 = 00000110 2 = 00000010 4 = 00000100 4 = 00000100 0 = 00000000 8 = 00001000 Sum = 8 |

Got a thought to share or found a

bug in the code?

We'd love to hear from you:

Name: | |

Email: | (Your email is not shared with anybody) |

Comment: |

Facebook comments:

Site Owner: Sachin Goyal