A Simple Interview Question
August 14, 2018
Today’s interview question comes from Apple:
Write a program to add two integers. You may not use the
+(addition) operator, but may use the++(increment by 1) or--(decrement by 1) operators. Be sure your solution works for both positive and negative inputs.
Your task is to write a program to add two integers. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here is my take with Julia (v. 1.0). Optimizing for number of iterations:
function add(x::Int64, y::Int64)
if x == 0
return y
elseif y == 0
return x
else
x_ = abs(x)
y_ = abs(y)
ind = argmin([x_, y_])
end
The expression (- x (- y)), equivalently x – -y for infix programmers, seems to meet the conditions of the problem.
Haskell.
decr :: Integral a => a -> a decr = subtract 1 incr :: Integral a => a -> a incr = (+1) add :: Integral a => a -> a -> a add x y | y < 0 = add (decr x) (incr y) | y == 0 = x | y > 0 = add (incr x) (decr y) main = do print $ add (-4) (-5) print $ add (-4) 5 print $ add 4 (-5) print $ add 4 5Here’s a solution in C.
#include <stdio.h> #include <stdlib.h> int add(int a, int b) { while (a > 0) { --a; ++b; } while (a < 0) { ++a; --b; } return b; } int main(int argc, char* argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s INT INT\n", argv[0]); return EXIT_FAILURE; } int a = atoi(argv[1]); int b = atoi(argv[2]); int result = add(a, b); printf("%d\n", result); return EXIT_SUCCESS; }Examples:
function sum(a, b) {
return a – (-b);
}
Instead of the add instruction, let’s use <<, >>, &, ==, ++, and — to implement a classical binary adder. Because Python automatically promotes ints to bignums, we special case -1 to prevent infinite regress.
def add(a, b, carry=0): if a == -1: carry -= 1 a = 0 if b == -1: carry -= 1 b = 0 if a == b == 0: return carry if a & 1: carry += 1 if b & 1: carry += 1 r = add(a >> 1, b >> 1, carry >> 1) << 1 if carry & 1: r += 1 return rAnother approach in Python.
def add(a, b): return 2*a if a == b else (a*a - b*b) // (a - b)