leetcode191题 题解 翻译 C语言版 Python版
2016-02-11 22:28
399 查看
191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming
weight).
For example, the 32-bit integer ’11' has binary representation
so the function should return 3.
191.比特1的数量
写一个函数,接收一个无符号的整型,返回其含有的比特1的数量,这东西也称为海明距离。
比如说,32位的整数11用二进制表示:
00000000000000000000000000001011,
所以函数应该返回3。
思路:把n不停地向右移位,取出移出的比特,进行记录累加即可。取出最右端的比特可以用模2,也可以与1进行与运算,如果等于1的话就记录,然后将n右移1位。注意右移表达式n >> 1不会改变n的值,而是会返回移位后的值,需要将值重新赋给n。
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming
weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
191.比特1的数量
写一个函数,接收一个无符号的整型,返回其含有的比特1的数量,这东西也称为海明距离。
比如说,32位的整数11用二进制表示:
00000000000000000000000000001011,
所以函数应该返回3。
思路:把n不停地向右移位,取出移出的比特,进行记录累加即可。取出最右端的比特可以用模2,也可以与1进行与运算,如果等于1的话就记录,然后将n右移1位。注意右移表达式n >> 1不会改变n的值,而是会返回移位后的值,需要将值重新赋给n。
int hammingWeight(uint32_t n) { int num = 0; while(n){ if ((n&1) == 1){ num++; } n >>= 1; } return num; }
class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ num = 0 while n != 0: if (n&1) == 1: num += 1 n >>= 1 return num
相关文章推荐
- C++迭代器
- 链表ADT C语言实现
- neuq oj 1017平面切割(特别版)C++
- ASCII编码
- neuq oj 1016 Roliygu and Yilan C++
- Chapter 1-03
- neuq oj 1015同因查找C++
- C++11 转移语义 (Move Sementics) 和精确传递 (Perfect Forwarding)
- C语言连接mysql数据库查询中文的数据表乱码问题
- C语言的一些小知识
- C语言 实现base64
- C语言 实现base64
- c语言中结构,动态分配内存的理解
- C语言连接mysql简单查询实例入门-mysql_init,mysql_real_connect,mysql_query,mysql_close等
- C++中vector的实现
- 北电C语言笔试题(1)
- neuq oj1014 等差数列C++
- neuq oj 1013 求偶数和 C++
- bzoj3110 K大数查询
- [c++] 友元详解