官方解答 · 置頂Java
官方解答|匯入紀錄復原
官方解答|匯入紀錄復原
解題思路
逐筆解析十進位整數,先 trim。解析後驗證「任何整數」,失敗主動拋 IllegalArgumentException;解析錯也因 NumberFormatException 繼承 IllegalArgumentException 而被捕捉。復原規則:捕捉錯誤後略過該筆,接著處理下一筆。 最後計算交錯加減。
正確性與邊界
補值直接加入保留清單,不再驗證;第一次錯誤停止與每次錯誤清空保留資料都在 catch 明確執行。空清單統計為 0,交錯加減按保留後順序。
複雜度
設總文字長度為 L、筆數為 n。時間 O(L+n),額外空間 O(n)。
公開範例
輸入 {"texts": ["0"]},依上述步驟得到 0。
下方程式可直接取代起始碼;使用 Java 11,入口為 Solution.solve。
CodeSprout 官方解答 · 題意分析、解題步驟與完整參考程式
import java.util.*;
public class Solution {
private static int aggregate(List<Integer> values) {
int answer = 0;
for (int i = 0; i < values.size(); i++)
answer += (i % 2 == 0 ? values.get(i) : -values.get(i));
return answer;
}
public static int solve(String[] texts) {
List<Integer> values = new ArrayList<>();
for (String text : texts) {
try {
int x = Integer.parseInt(text.trim(),10);
if (!(true)) throw new IllegalArgumentException();
values.add(x);
} catch (IllegalArgumentException error) {
// Skip this record and continue.
}
}
return aggregate(values);
}
}
留言討論 0
登入 後就能留言,一起討論不同的寫法。