Clarification in adding a two numbers without using any arithmetic operators
I understood how this solution works.
int add_no_arithm(int a, int b) {
if (b == 0) return a;
int sum = a ^ b; // add without carrying
int carry = (a & b) << 1; // carry, but don’t add
return add_no_arithm(sum, carry); // recurse
}
But the author comments over this problem as:
"Our first instinct in problems like these should be that we’re going to have to work with bits. Why? Because when you take away the + sign, what other choice do we have? Plu开发者_C百科s, that’s how computers do it."
What is the author trying to imply?
What he means is quite simple - if you don't have the +
operation, you'll need to replicate the behaviour on the bit level of an integer. The code you posted is about the same of what the +
operation does natively in the ALU (algorithmic logical unit, the place where calculations take place in a CPU).
Yeah, this is what is used - http://en.wikipedia.org/wiki/Adder_%28electronics%29
精彩评论