[英]Find the sum of an int array - leaving out all numbers between a 6 and a 7, inclusive
我想編寫一個程序,將所有數字加到一個整數數組中-例外! 由於數字6並不是最好的數字,因此我建議我們排除數字的所有部分,這些部分以6開頭,以7結尾(包括7)。 每6個數字后總是7個數字 ,但反之亦然。
以下是輸入數組及其預期輸出的一些示例:
sum67([1, 2, 2, 6, 99, 99, 7]) = 5
排除6和7之間的所有數字。
sum67([1, 2, 2]) = 5
6或7。
sum67([1, 1, 6, 7, 2]) → 4
不包括6或7。
以上所有測試均通過。
同樣,方法標頭是固定的,我只能更改方法的主體。 這是我嘗試的代碼:
public int sum67(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
// Adding all numbers that are not a 6
if (nums[i] != 6) sum += nums[i];
}
for (int j = 0; j < nums.length; j++) {
// check for the sixes - the lower bound exclusive
if (nums[j] == 6) {
for (int k = j + 1; k < nums.length; k++) {
// check for the sevens - the upper bound inclusive
if (nums[k] == 7) {
// take away all the numbers between the 2 bounds, including the 7
for (int m = j + 1; m <= k; m++) {
sum -= nums[m];
}
}
}
}
}
return sum;
}
上面的程序不僅無效 ,而且非常混亂。 特別是,它無法通過以下測試,其中包括:
sum67([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) = 2
實際輸出為-463
!
sum67([2, 2, 6, 7, 7]) = 11
實際輸出是-3
。
所以本質上:
錯誤行在我的代碼中在哪里?
有沒有寫這個程序,不具有盡可能多的循環和嵌套一個更好的辦法if
S'
public int sum67(int[] arr) {
int sum = 0;
boolean isIn67 = false;
for (int i = 0 ; i < arr.length ; i++) {
if (arr[i] == 6) {
isIn67 = true;
continue;
} else if (arr[i] == 7 && isIn67) {
isIn67 = false;
continue;
}
if (!isIn67) {
sum += arr[i];
}
}
return sum;
}
以上是我的嘗試。 說明:
isIn67
的變量,它指示arr[i]
是否在6-7范圍內,因此不應將其添加到總和中 isIn67
設置為true。 isIn67
為true時,我們將isIn67
設置為false。 continue
,這樣我們就不算那些7 in67
,則將元素添加到總和中。 代碼的問題可能是您嵌套太多了。 減去多余數字的行嵌套在外部循環中,因此它執行的次數可能比預期的多得多,從而使結果為負數。
您使用的邏輯不能代表您想要做什么。 以第一個示例為例,並考慮第二個循環(因此,您已經總結了所有內容)
<=
-這是第二個示例中-3
的原因) 我建議您用筆和紙跟隨您的代碼以查看其工作原理。 一個更簡單的解決方案是完全執行您想要的操作:
int sum = 0;
boolean noLikey = false;
for (int i = 0; i < nums.length; i++) {
if (! noLikey && nums[i] == 6 ) noLikey = true;
if ( noLikey ) {
if ( nums[i] == 7 ) noLikey = false;
continue;
}
sum += nums[i];
}
當然,這假定6
后面總是跟着7。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.