开发者

Clarification in adding a two numbers without using any arithmetic operators

开发者 https://www.devze.com 2023-03-26 16:37 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号