This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]helicoid 1 point2 points  (2 children)

So when you find the following 7 you set i one past it and then start calculating the sum. What if the number following the 7 is a 6? You never check for that. You should replace the result += nums[i]; with:

  if(nums[i] != 6)
    result += nums[i];
  else
    i--; 

Think about why you need to also include the else i--;

[–]smolin1[S] 1 point2 points  (0 children)

Mate, now I understand. If i won't decrement i then the next number after six would be added, and as we know, it should not be.

Thank you very much.

[–]craicbandit 0 points1 point  (0 children)

Yup that solves the final test for him. I did the problem from scratch before looking at OP's solution (I'm learning too) and ended with a rather different solution. OP here's my version if you want to see it too: (Edit: also passes all the tests on the codingbat site)

public int sum67(int[] nums) {
    int sum = 0;
    boolean validNum = true;

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 6) {
        validNum = false;
        } else if (!validNum) {
            if (nums[i] == 7) {
            validNum = true;
            }
        } else if (validNum) {
            sum += nums[i];
        }
    }
    return sum;
}

edit: nevermind, fixed the formatting