Uri Online Judge逻辑数学题求助:提交代码显示Wrong Answer排查
Hey there, let's break down why your code is failing and fix it step by step!
The Core Problem: Input Handling Mistake
Your main issue lies in how you're reading the input values. Let's walk through what's going wrong:
- You correctly grab
n(the number of test cases) fromlines[0]initially. - But when you start looping, you use
lines.shift()to get eachj. The firstshift()call removes thenvalue from thelinesarray—so your firstjends up being the originallines[0](which isnitself) instead of the first actual test number. This misalignment between your input reading and expected test cases is why you're getting a Wrong Answer.
Minor Cleanup: Duplicate Variable Declaration
You declared var n twice at the top of your code. While JavaScript allows this, it's unnecessary and can create confusion. You can safely remove the first var n; line since you re-declare and assign it right after.
Corrected Code
Here are two working versions, each with a slightly different input-handling approach:
Approach 1: Direct Index Access
This version uses array indexes to avoid modifying the original lines array:
var j; var n = parseInt(lines[0]); // Loop through test cases starting from index 1 (since lines[0] is the count) for (var i = 1; i <= n; i++) { j = parseInt(lines[i]); if (j === 0) { console.log("NULL"); } else if (j % 2 !== 0 && j < 0) { console.log("ODD NEGATIVE"); } else if (j % 2 !== 0 && j > 0) { console.log("ODD POSITIVE"); } else if (j % 2 === 0 && j > 0) { console.log("EVEN POSITIVE"); } else { console.log("EVEN NEGATIVE"); } }
Approach 2: Shift After Removing the Count
If you prefer using shift(), first remove the count from the array before processing test cases:
// Grab the count and remove it from the lines array immediately var n = parseInt(lines.shift()); var j; // Loop exactly n times to process each test case for (var i = 0; i < n; i++) { j = parseInt(lines.shift()); // Your condition checks stay identical if (j === 0) { console.log("NULL"); } else if (j % 2 !== 0 && j < 0) { console.log("ODD NEGATIVE"); } else if (j % 2 !== 0 && j > 0) { console.log("ODD POSITIVE"); } else if (j % 2 === 0 && j > 0) { console.log("EVEN POSITIVE"); } else { console.log("EVEN NEGATIVE"); } }
Why These Fixes Work
Both approaches ensure you're reading the correct test numbers instead of accidentally including the count value in your processing. This aligns your input handling with what URI Online Judge expects, which should resolve the Wrong Answer error.
内容的提问来源于stack exchange,提问作者Joe Hill

