LeetCode By Go

[LeetCode By Go 76]Add to List 1

2017-08-31  本文已影响2人  miltonsun

本体不能用go语言写,因此用C语言

题目

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.

解题思路

判断数字n最低位是否为1,若为1 ,结果ret加1,然后右移一位,循环知道数字n == 0

代码

int hammingWeight(uint32_t n) {
    int ret = 0;
    while (n > 0) {
        if (n % 2 == 1) {
            ret++;
        }
        n = n >> 1;
    }
    
    return ret;
}
上一篇 下一篇

猜你喜欢

热点阅读