public class Solution {
    public int HammingWeight(uint n) {
        var list = new List<uint>();

            do
            {
                var x = n % 2;
                list.Add(x);
                n = n / 2;
            } while (n != 0);

            var count = 0;

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] == 1)
                {
                    count++;
                }
            }

            return count;
    }
}

https://leetcode.com/problems/number-of-1-bits/#/description

补充一个python的实现:

1 class Solution:
2     def hammingWeight(self, n: int) -> int:
3         ret = 0
4         while n != 0:
5             cur = n % 2
6             if cur == 1:
7                 ret += 1
8             n = n // 2
9         return ret

 

posted on 2017-04-19 21:59  Sempron2800+  阅读(103)  评论(0编辑  收藏  举报