JavaScript或门操作实现?HackerRank题目代码求助
Hey there! Let's break down the issues in your code and fix them up properly.
The Core Problem: Incorrect OR Operation
Your current or function uses JavaScript's logical OR (||), which doesn't do what you need here. When you pass two strings like '10101' and '11100' to it, || just returns the first "truthy" string (which is always the first one here, since non-empty strings are truthy). It doesn't perform a bitwise OR on each character of the string, which is exactly what the ACM Team problem requires.
How to Fix the Bitwise OR
You need to iterate over each character position in the two strings, convert each character to a number, perform a bitwise OR (|) on the pair, then convert it back to a string and build the result. Here's a corrected version of the OR function:
function bitwiseOr(a, b) { let result = ''; // Iterate over each character position (assuming both strings are same length) for (let i = 0; i < a.length; i++) { // Convert chars to numbers, do bitwise OR, then back to string const bitA = parseInt(a[i], 10); const bitB = parseInt(b[i], 10); result += (bitA | bitB).toString(); } return result; }
Adding the Required Logic for the Problem
Right now, your acmTeam function just logs values but doesn't return the required result: an array where the first element is the maximum number of topics any team knows, and the second element is how many teams achieve that maximum. Let's update the function to track these values:
function acmTeam(topic) { let maxTopics = 0; let teamCount = 0; for (let i = 0; i < topic.length; i++) { const iItem = topic[i]; for (let j = i + 1; j < topic.length; j++) { const jItem = topic[j]; const combined = bitwiseOr(iItem, jItem); // Count the number of '1's in the combined string const currentTopics = combined.split('').filter(bit => bit === '1').length; // Update max and count if (currentTopics > maxTopics) { maxTopics = currentTopics; teamCount = 1; } else if (currentTopics === maxTopics) { teamCount++; } } } return [maxTopics, teamCount]; } // Test with your sample input const topic = [ '10101', '11100', '11010', '00101' ]; const out = acmTeam(topic); console.log(out); // Should log [5, 2] which matches the sample expected output
Key Changes Explained
- Replaced the logical OR with a proper bitwise OR implementation that works on string-based binary values.
- Added tracking for the maximum number of topics and the number of teams that reach that maximum.
- Calculated the number of known topics by counting '1's in the combined result string.
- Made the function return the required result array instead of just logging values.
If you run this corrected code with your sample input, it should output [5, 2]—which is the correct answer for that test case.
内容的提问来源于stack exchange,提问作者kenpeter

