Skip to content
Advertisement

Sum of numbers in array, not counting 13 and number directly after it (CodingBat puzzle)

The Question:

Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

My Code:

JavaScript

Where It’s Failing:

JavaScript

Advertisement

Answer

Your problem is when x is zero. x - 1 will be -1 so it will get the last element of your list (13). To fix it, don’t test x - 1 if x is zero:

JavaScript

In Python, when you pass a negative index to a list it accesses its elements backwards, so:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement