美文网首页LeetCode By Go
[LeetCode By Go 76]Add to List 1

[LeetCode By Go 76]Add to List 1

作者: miltonsun | 来源:发表于2017-08-31 09:48 被阅读2次

本体不能用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;
}

相关文章

网友评论

    本文标题:[LeetCode By Go 76]Add to List 1

    本文链接:https://www.haomeiwen.com/subject/dxuxjxtx.html