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.
Here’s a solution in C.
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.
Another approach in Python.