我想使用Java编写一个程序,它可以计算一个数组中所有数字的总和——但有个例外!因为数字13非常不吉利,所以我建议我们完全排除数字13以及直接跟在13后面的数字(如果有的话)。
这个程序名叫做
以下是我为
这个程序名叫做
sum13
,以下是一些输入和输出示例:
sum13([1,2,2,1]) = 6
这个很正常,没有13。
sum13([5, 13, 2]) = 5
排除了13和直接跟在13后面的数字。
sum13([13, 13]) = 0
数组只包含13,因此两个13都不包括在内。
sum13([1, 2, 13, 2, 1, 13]) = 4
这是一个稍微复杂一些的例子。以下是我为
sum13
编写的代码:public int sum13(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
// we start by adding all the non-13s to the sum
if (nums[i] != 13) sum += nums[i];
}
// now we go back and remove all the non-13s directly after a 13
for (int j = 0; j < nums.length; j++) {
// the outermost loop checks if the numbers are a 13
if (nums[j] == 13 && j < nums.length - 1) {
for (int k = j + 1; k < nums.length; k++) {
// this loop checks that the number after the 13 is not a 13
if (nums[k] != 13) {
sum -= nums[k];
break;
}
}
}
}
return sum;
}
上述程序虽然能够正常工作,但是看起来相当混乱!
有没有更好的编写程序的方法,不需要包含多个循环和嵌套的 if
语句?