leetcode191题 题解 翻译 C语言版 Python版
来源:互联网 发布:js 自定义属性 data 编辑:程序博客网 时间:2024/06/06 12:50
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 representation00000000000000000000000000001011
, 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
0 0
- leetcode191题 题解 翻译 C语言版 Python版
- leetcode292题 题解 翻译 C语言版 Python版
- leetcode258题 题解 翻译 C语言版 Python版
- leetcode104题 题解 翻译 C语言版 Python版
- leetcode237题 题解 翻译 C语言版 Python版
- leetcode226题 题解 翻译 C语言版 Python版
- leetcode283题 题解 翻译 C语言版 Python版
- leetcode100题 题解 翻译 C语言版 Python版
- leetcode242题 题解 翻译 C语言版 Python版
- leetcode171题 题解 翻译 C语言版 Python版
- leetcode235题 题解 翻译 C语言版 Python版
- leetcode206题 题解 翻译 C语言版 Python版
- leetcode328题 题解 翻译 C语言版 Python版
- leetcode70题 题解 翻译 C语言版 Python版
- leetcode83题 题解 翻译 C语言版 Python版
- leetcode263题 题解 翻译 C语言版 Python版
- leetcode326题 题解 翻译 C语言版 Python版
- leetcode231题 题解 翻译 C语言版 Python版
- Android开发学习之路--Broadcast Receiver之初体验
- 27. Remove Element LeetCode
- PECL 和 PEAR 有什么区别?
- 【leetcode】Array——word search(79)
- 关于编程语言中的显式\隐式初始化
- leetcode191题 题解 翻译 C语言版 Python版
- 面试笔试杂项积累-leetcode 211-215
- 26. Remove Duplicates from Sorted Array LeetCode
- 【leetcode】Array——Unique Paths(62)
- django学习之 pdf报表(表格)生成
- Java—设计模式(工厂模式)
- java常见问题
- 66. Plus One LeetCode
- 继承与多态的学习