191. Number of 1 Bits 二进制中1的个数
[抄题]:
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.
[暴力解法]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
[一句话思路]:
用 & 符号来统计1的个数
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
n = n >>> 1 是一个运算之后的数,也需要赋值
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
无符号右移可以去掉1
[复杂度]:Time complexity: O() Space complexity: O()
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int ones = 0; while (n != 0) { ones += (n & 1); n = n >>> 1; } return ones; } }