【LeetCode】位1的个数 题目
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
思路1:while循环,n%2 ,统计余数中1的个数。
思路2:循环和位移动,for循环32次,代表n的32位,令m初值为1,m与n按位与运算,结果不为0,表示该位为1;每次循环m左移一位。
思路3:从官方题解得到的最大收获,get一个小技巧,也是小知识点。
数字n对应二进制数中最低位的1所在位,数字n-1对应二进制数的相应位数字为0,所以n&(n-1)能使最后一位1变成0。
按照此思路,while(n)循环,令n=n&(n-1),当n不为0时循环,每循环一次有一个1变成0,即统计了1的个数。