Reputation: 17
I am working on practice coding problems and i came across this task.
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
I came up with the right solution but i am not sure about one thing.
public int sum13(int[] nums)
{
int sum = 0;
for(int i = 0; i < nums.length; i++)
{
if(nums[i] == 13)
i++;
else
sum += nums[i];
}
return sum;
}
In one of the test cases output is 4, sum13([1, 2, 13, 2, 1, 13]) → 4 .
My question is ,in my "if" statement i incremented the counter by 1. Why did it not add the next element to the sum? Why did it skip the next element even though I'm only incrementing by 1 ?
Upvotes: 1
Views: 2221
Reputation: 157
This code works fine:-
public int sum13(int[] nums) {
int sum=0;
for(int i=0;i<=nums.length-1;i++){
if(nums[i]!=13){
sum+=nums[i];
if(i>0 && nums[i-1] == 13)
sum -= nums[i];
}
}
return sum;
}
Upvotes: 0
Reputation: 140523
Your problem is here:
if(nums[i] == 13)
i++;
There is no point in increasing the index; that just makes you increase your loop counter twice in one iteration!
So, just go with
if(nums[i] != 13) {
sum += nums[i];
}
instead (no else here; and: better always use { braces }; even when it is just a one-liner!)
And as you actually do not need that index at all, you could use the for-each loop style:
for (int num : nums ) {
if (num != ...
Even less chance for messing up your index!
Upvotes: 2
Reputation: 60788
You are skipping 13 and the number after. You are incrementing i
twice.
Upvotes: 1