您的位置:首页 > 职场人生

剑指Offer面试题10 & Leetcode191

2017-05-08 11:06 411 查看

剑指Offer面试题10 & Leetcode191

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).

解题思路

  考虑:这题的巧妙之处是能够想到n&(n-1)可以去掉n二进制末尾的1,例如7的二进制为111,(7-1)的二进制为110,111&110=110。如此循环,当n为0时便可得出1的个数。

Solution

public int hammingWeight(int n) {
int count = 0;
while(n!=0){
count++;
n = n & (n-1);
}
return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息