To solve the problem of counting the number of 1s in the binary representation of an integer, we can use Brian Kernighan's Algorithm, which efficiently counts the set bits (1s) by repeatedly flipping the least significant 1 to 0 until the number becomes zero. This approach runs in O(k) time, where k is the number of 1 bits, making it optimal for this task.
Approach
- Handle Negative Numbers: For negative integers, we convert them to their 32-bit unsigned equivalent using a mask (
0xFFFFFFFF) to avoid infinite loops (since negative numbers in two's complement have leading 1s). - Count Set Bits: Use Brian Kernighan's Algorithm:
- For a number
n,n & (n-1)flips the least significant 1 to 0. - Increment the count each time we flip a 1 to 0.
- Repeat until
nbecomes zero.
- For a number
Solution Code
def count_ones(n: int) -> int:
count = 0
# Convert negative numbers to 32-bit unsigned equivalent
if n < 0:
n = n & 0xFFFFFFFF
while n:
count += 1
n = n & (n - 1)
return count
Explanation
- Negative Number Handling: The mask
0xFFFFFFFFconverts a negative integer to its 32-bit unsigned form. For example,-1becomes4294967295(32 1s). - Brian Kernighan's Algorithm:
- For
n = 6(binary110),n & (n-1) = 110 & 101 = 100(count increases to 1). Next,100 & 011 = 0(count increases to 2, loop ends). - This method skips over 0 bits, so it's faster than checking each bit individually.
- For
This solution efficiently counts the number of 1 bits for both positive and negative integers, adhering to standard 32-bit unsigned representation for negatives. The time complexity is O(k) (k = number of 1 bits), and space complexity is O(1).
Answer: The function count_ones as defined above returns the number of 1s in the binary representation of the input integer. For example, count_ones(5) returns 2 (binary 101), and count_ones(-1) returns 32 (32-bit unsigned).
The final answer is the code provided, which solves the problem optimally.


作者声明:本文包含人工智能生成内容。