[LeetCode By Go 76]Add to List 191. Number of 1 Bits

本体不能用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;
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/971139a46623
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞