Leetcode 2595: Number of Even and Odd Bits

grid47
grid47
Exploring patterns and algorithms
Feb 21, 2024 5 min read

Given a positive integer n, return an array containing the number of 1 bits at even indices and odd indices in the binary representation of n. The binary digits are indexed from right to left, starting at index 0. The first element of the array should represent the number of 1 bits at even indices, and the second element should represent the number of 1 bits at odd indices.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n`.
Example: For `n = 50`.
Constraints:
• 1 <= n <= 1000
Output: Return an array with two elements: the first element is the count of `1` bits at even indices and the second element is the count of `1` bits at odd indices.
Example: For `n = 50`, the output is `[1, 2]`.
Constraints:
• The output is an array of two integers.
Goal: To efficiently count the `1` bits at even and odd indices in the binary representation of `n`.
Steps:
• 1. Convert `n` to its binary representation.
• 2. Iterate through each bit of the binary representation, counting the `1` bits at even and odd indices separately.
• 3. Return the result as an array with the counts of even and odd indexed `1` bits.
Goal: The value of `n` is between 1 and 1000.
Steps:
• 1 <= n <= 1000
Assumptions:
• The binary representation of `n` will not exceed 10 bits in length.
Input: For `n = 50`
Explanation: The binary representation of `50` is `110010`. There is one `1` at an even index (index 1), and two `1`s at odd indices (indices 4 and 5). Thus, the output is `[1, 2]`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus