You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The solution to add two numbers is incorrect and works purely by accident only because types of both inputs are Int. If one of them is changed to Long, the answers would be incorrect. Also very simple addition like add(3, -3) will result in a stackoverflow if the function is not marked tailrec because it takes 2^32 - 3 iterations to get b from -3 to 0.
Provided solution is tailrec fun add(x: Int, y: Int): Int = if (y == 0) x else add(inc(x), dec(y)).
The correct solution would be
tailrec fun add(a: Int, b: Int): Int =
when {
(b == 0) -> a
(b > 0) -> add(inc(a), dec(b))
else -> add(dec(a), inc(b))
}
The text was updated successfully, but these errors were encountered:
The solution to add two numbers is incorrect and works purely by accident only because types of both inputs are Int. If one of them is changed to Long, the answers would be incorrect. Also very simple addition like
add(3, -3)
will result in a stackoverflow if the function is not marked tailrec because it takes2^32 - 3
iterations to get b from -3 to 0.Provided solution is
tailrec fun add(x: Int, y: Int): Int = if (y == 0) x else add(inc(x), dec(y))
.The correct solution would be
The text was updated successfully, but these errors were encountered: