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
}
There are a couple of suggestions for figuring out this problem. 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? Plus, that’s how computers do it. Our next thought in problems like these should be to really, really understand how you add. Walk through an addition problem to see if you can understand something new—some pattern—and then see if you can replicate that with code.
Your interviewer is looking for two things in this problem:
- Can you break down a problem and solve it?
- Do you understand how to work with bits?
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.