zoukankan      html  css  js  c++  java
  • 【LeetCode】面试题15. 二进制中1的个数

    题目:

    思路:

    1、直观思路就是将十进制数转换成二进制后,统计二进制中1的个数。可以在转换过程中统计,也可以转换后将二进制字符串转换成int列表累加。

    2、基于位操作的方法更简单

    • 逐位判断: 利用与运算判断最右位是否为1,然后无符号右移
    • 利用n&(n-1)

    代码:

    Python

    class Solution(object):
        def hammingWeight(self, n):
            """
            :type n: int
            :rtype: int
            """
            # # 进制转换
            # count = 0
            # while n:
            #     count += n % 2
            #     n = n // 2
            # return count
    
            # # 逐位操作
            # count = 0
            # while n:
            #     count += n & 1
            #     n >>= 1
            # return count
    
            # 利用n&(n-1)
            count = 0
            while n:
                count += 1
                n &= n-1
            return count
    

    相关问题

  • 相关阅读:
    L1-021 重要的话说三遍
    L1-020 帅到没朋友
    pytest--钩子
    pytest--allure
    pytest--常用插件
    pytest--高级用法
    pytest--配置文件
    pytest--控制运行
    pytest--fixture
    pytest--使用前提
  • 原文地址:https://www.cnblogs.com/cling-cling/p/12965410.html
Copyright © 2011-2022 走看看