Skip to content

Instantly share code, notes, and snippets.

@AndresRodz
Created February 13, 2014 00:49
Show Gist options
  • Save AndresRodz/8967639 to your computer and use it in GitHub Desktop.
Save AndresRodz/8967639 to your computer and use it in GitHub Desktop.
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 public int sum13(int[] nums)
import java.util.Scanner;
public class SumArray13 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int positions = input.nextInt();
int[] myarray = new int[positions];
for (int x = 0; x < myarray.length; x++) {
myarray[x] = input.nextInt();
}
int sum = sum13(myarray);
System.out.println(sum);
}
public static int sum13(int[] myarray) {
int sum = 0;
if (myarray.length == 0) {
System.out.println(sum);
} else {
for (int i = 0; i < myarray.length; i++) {
if (myarray[i] != 13) {
sum = sum + myarray[i];
} else if (myarray[i] == 13 && i < myarray.length - 1) {
myarray[i] = 0;
myarray[i + 1] = 0;
}
}
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment