剑指Offer面试题10 & Leetcode191

剑指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-java实现,leetcode-java)