LeetCode 191 Number of 1 Bits(1 比特的数字们)

简介: 版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50506429 翻译写一个函数获取一个无符号整型数,并且返回它的“1”比特的数目(也被叫做Hamming weight)。
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50506429

翻译

写一个函数获取一个无符号整型数,并且返回它的“1”比特的数目(也被叫做Hamming weight)。

例如,一个32位整型数“11”,转换成二进制是00000000000000000000000000001011,所以这个函数应该返回3。

原文

Write a function that takes an unsigned integer and returns the number of1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer11' has binary representation 00000000000000000000000000001011, so the function should return 3.

分析

这道题我之前遇到过,这里就直接贴结果了,稍候我整理一篇关于位运算的博客出来。欢迎大家再来……

代码

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        while (n) {
            ++count;
            n = (n - 1) &  n;
        }
        return count;
    }
};
目录
相关文章
|
5月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
64 1
|
6月前
【Leetcode -704.二分查找 -709.转换成小写字母 -717.1比特与2比特字符】
【Leetcode -704.二分查找 -709.转换成小写字母 -717.1比特与2比特字符】
19 0
|
6月前
【Leetcode -292.Nim游戏 -326. 3的幂 -338.比特位计数】
【Leetcode -292.Nim游戏 -326. 3的幂 -338.比特位计数】
19 0
|
2月前
LeetCode题 338比特位计数,20有效的括号,415字符串相加
LeetCode题 338比特位计数,20有效的括号,415字符串相加
35 0
|
3月前
leetcode-338:比特位计数
leetcode-338:比特位计数
17 0
|
3月前
leetcode-717:1比特与2比特字符
leetcode-717:1比特与2比特字符
18 0
|
5月前
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
21 0
|
Java Linux
LINUX编译OPENJDK:The tested number of bits in the target (0) differs from the number of bits expected
LINUX编译OPENJDK:The tested number of bits in the target (0) differs from the number of bits expected
162 0
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
|
存储 前端开发 算法
LeetCode只出现一次的数字使用JavaScript解题|前端学算法
LeetCode只出现一次的数字使用JavaScript解题|前端学算法
110 0