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. sum13([1, 2, 2, 1]) → 6 sum13([1, 1]) → 2 sum13([1, 2, 2, 1, 13]) → 6 how do you proceed?
you design an algorithm.. which searches for 13s in an O(N) procedure.. then if it finds thirteens in pos i array[i]=array[i+1]=0 and then in an other O(N) procedure calculates the sum.. it can be done in one procedure.. think of how ;)
loop it and sum until you see 13 as array element
function sum13() numbers[] <- [0, 1, .., n] int sum <- 0 for( int i = 0; i < numbers.length; i++) if(numbers[i] == 13) return sum; else sum <- sum + numbers[i] return sum;
Break your question into individual sentences. Make them into comments. Write the code for each sentence. A LOT of programming is really learning how to break problems down (decomposing) to a point that they can be coded (which is describing how to solve the problem to a dumb, albeit extremely fast, machine).
Join our real-time social learning platform and learn together with your friends!