Amazon Interview Question
SDE-2sCountry: India
Interview Type: Phone Interview
Ha, yeah...the problem as stated here might allow that, but that seems like an awfully weird interview question.
I was working off the assumption that you needed to take a number and actually mutate it to zero without doing a direct assignment...kind of like how in x86, when you want to zero out a register, you do "xor (reg), (reg)".
XOR the number with itself.
You can do this in a language like Java or C# with a simple number ^ number;
The result of an XOR between two bits is only 1 when one, but not both, of the bits are 1.
Logically, you can see that if you XOR a number with itself, any 1 bits will go to zero because 1 ^ 1 = 0. Any bits that are 0 will stay zero, because 0 ^ 0 = 0. So any number XOR'd with itself is always 0.
Can't you just return 0 regardless of the input?
- chriscow January 26, 2014