内容中心

2026年口碑好的医药氮气发生器可靠供应商推荐-苏州希特高纯气体设备有限公司

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

  1. 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).
  2. 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 n becomes zero.

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 0xFFFFFFFF converts a negative integer to its 32-bit unsigned form. For example, -1 becomes 4294967295 (32 1s).
  • Brian Kernighan's Algorithm:
    • For n = 6 (binary 110), 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.

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.

苏州希特高纯气体设备有限公司

苏州希特高纯气体设备有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?