Calculate n + 1 without using + or - or * or /
As the title asks! My buddy came across this while preparing for an interview.
All I could think of is implementing a full adder in software but I'm thinking there has to be a better solution...help!
All I could think of is implementing a full adder in software but I'm thinking there has to be a better solution...help!
18 comments
[ 4.8 ms ] story [ 52.5 ms ] threadint add( int a, int b ) { while ( a ) { int c = a & b; b ^= a; a = c << 1; } return b; }
int sub( int a, int b ) { return add( a, add( ~b, 1 ) ); }
int mul( int a, int b ) { int c = 0; while ( a ) { if ( a & 1 ) c = add( c, b ); a >>= 1; b <<= 1; } return c; }
plus1 = Succ
Probably not the answer they were looking for, but it was the first thing that came into my head.
In some situations you may be data rich but function poor. Like embedded devices where you have a limited instruction set, 128bytes of RAM, but access to megs of ROM for program/data.
Python.
Too simple? I didn't use any of the signs, and it demonstrates knowledge of the python standard library!
EDIT: Whoops, seems the idea of using the sum() function (or operator) has been dismissed elsewhere. Time to study some more languages, I think.
round($n.'.9')
x=n++;
https://gist.github.com/1063990
uses only bit shits, bitwise XOR, and bitwise AND
I would imagine they meant not to use the operations, not just the symbols.