Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Adding numbers

Adding numbers

How to add numbers without using operators

Avatar for Ian Randall

Ian Randall

October 03, 2013

Other Decks in Programming

Transcript

  1. Bitwise Operators • ‘AND’ - takes two binary inputs. Returns

    1 if both are 1, otherwise 0 0  and  0  -­‐-­‐>  0 0  and  1  -­‐-­‐>  0 1  and  0  -­‐-­‐>  0 1  and  1  -­‐-­‐>  1 Friday, 4 October 13
  2. Bitwise Operators • ‘XOR’ - Exclusive OR. Returns 1 if

    one or the other inputs is 1, but not neither and not both. 0  xor  0  -­‐-­‐>  0 0  xor  1  -­‐-­‐>  1 1  xor  0  -­‐-­‐>  1 1  xor  1  -­‐-­‐>  0 Friday, 4 October 13
  3. Bit Shifting • Left-shift - moves all the 1’s across

    to the left        0001  0110    (22) -­‐>    0010  1100    (44) • Right-shift - moves all the 1’s across to the right        0001  0110    (22) -­‐>    0000  1011    (11) Friday, 4 October 13
  4. The Formula • Start with two numbers: x and y

    set a  =  (x  AND  y) set b  =  (x  XOR  y) set x  =  a left-shifted by 1 set y  =  b -- keep going until a is 0. The answer is b Friday, 4 October 13
  5. E.G. 10 + 7    1010 &  0111    -­‐-­‐-­‐-­‐

       0010  -­‐>  Left-­‐shifted  -­‐>  0100  (4)    1010 ^  0111    -­‐-­‐-­‐-­‐    1101  (13) Friday, 4 October 13
  6. E.G. 4 + 13    0100 &  1101    -­‐-­‐-­‐-­‐

       0100  -­‐>  Left-­‐shifted  -­‐>  1000  (8)    0100 ^  1101    -­‐-­‐-­‐-­‐    1001  (9) Friday, 4 October 13
  7. E.G. 8 + 9    1000 &  1001    -­‐-­‐-­‐-­‐

       1000  -­‐>  Left-­‐shifted  -­‐>  10000  (16)    1000 ^  1001    -­‐-­‐-­‐-­‐    0001  (1) Friday, 4 October 13
  8. E.G. 16 + 1    10000 &  00001    -­‐-­‐-­‐-­‐

       00000  -­‐>  Left-­‐shifted  -­‐>  00000  (0)    10000 ^  00001    -­‐-­‐-­‐-­‐    10001  (17) Friday, 4 October 13
  9. Adding Numbers in C int  add(int  x,  int  y) {

       int  a,b;    do  {        a  =  x  &  y;        b  =  x  ^  y;        x  =  a  <<  1;        y  =  b;    }  while  (a);    return  b; } Friday, 4 October 13
  10. recursion! int  add(int  x,  int  y) {    int  a,b;

       if  (x  ==  0)        return  y;    a  =  (x  &  y)  <<  1;    b  =  x  ^  y;    return  add(a,  b); } Friday, 4 October 13
  11. recursion! int  add(int  x,  int  y) {    if  (x

     ==  0)        return  y;    return  add((x  &  y)  <<  1,  x  ^  y); } Friday, 4 October 13
  12. just for fun... import  Data.Bits add  ::  (Bits  a)  =>

     a  -­‐>  a  -­‐>  a add  a  b    |  a  ==  0        =  b    |  otherwise  =  add  ((a  .&.  b)  `shiftL`  1)  (a  `xor`  b) https://gist.github.com/IanRandall/6775842 Friday, 4 October 13