内容中心

2026年排名好的销售人员人才招聘用户好评公司-浙江环讯人力资源有限公司

To solve the problem of counting the number of 1's in the binary representation of a number, we can use an efficient bitwise operation approach. Here's the step-by-step solution:

Approach

The key insight here is using the bitwise operation n & (n-1), which clears the least significant 1 bit in n each time it is applied. We count how many times this operation can be performed until n becomes 0—this count is the number of 1 bits in the binary representation of the original number. This method is efficient with a time complexity of O(k), where k is the number of 1 bits (better than O(number of bits) for string conversion methods).

Solution Code

def count_ones(n):
    count = 0
    while n > 0:
        n &= n - 1  # Clear the least significant 1 bit
        count += 1
    return count

# Example usage:
# print(count_ones(5))  # Output: 2 (binary: 101)
# print(count_ones(0))  # Output: 0
# print(count_ones(7))  # Output:3 (binary:111)

Explanation

  • Initialization: We start with a count of 0.
  • Loop: For each iteration, we use n &= n-1 to remove the rightmost 1 bit from n. This works because subtracting 1 from n flips all bits from the rightmost 1 bit to the end, and ANDing with the original n clears those flipped bits (thus removing the rightmost 1).
  • Count: Each time we clear a 1 bit, we increment the count.
  • Termination: The loop stops when n becomes 0, and we return the count of 1 bits.

This approach efficiently counts the 1 bits and handles all non-negative integers correctly. For negative numbers, you might need to consider two's complement representation, but the problem typically assumes non-negative inputs unless specified otherwise.

Answer: The Python function to count the number of 1's in the binary representation of a number is as shown above. For example, count_ones(5) returns 2, count_ones(7) returns 3, and count_ones(0) returns 0. The final code is:

def count_ones(n):
    count = 0
    while n > 0:
        n &= n - 1
        count += 1
    return count

浙江环讯人力资源有限公司



(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。

在线客服

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