剑指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; }
相关文章推荐
- 剑指Offer面试题9 & Leetcode70
- 剑指Offer面试题21 & Leetcode155
- 剑指Offer面试题8 & Leetcode153
- 剑指Offer面试题19 & Leetcode226
- 剑指Offer面试题7 & Leetcode232
- 《剑指Offer》面试题10:二进制中1的个数
- 《剑指offer》(面试题10):二进制中1的个数
- 《剑指offer》面试题10(二进制中1的个数)
- 剑指Offer面试题10:斐波那契数列
- 剑指offer 面试题19:二叉树的镜像(leetcode226. Invert Binary Tree) 题解
- 剑指offer 面试题20:顺时针打印矩阵及其变形(LeetCode54. Spiral Matrix旋转矩阵) 题解
- 剑指offer面试题10:二进制中1的个数
- 剑指offer面试题10 二进制中1的个数 java实现
- 剑指offer面试题10
- 剑指offer-面试题10:二进制中1的个数
- 剑指Offer 面试题11:数的整数次方(Leetcode50. Pow(x, n))【C库函数pow模拟】题解
- 剑指Offer面试题10(Java版):二进制中的1的个数
- #leetcode#191 Number of 1 Bits n&n-1的用处
- 剑指offer面试题10
- 剑指Offer面试题17 & Leetcode21