zoukankan      html  css  js  c++  java
  • [Leetcode]-Number of 1 Bits

    Number of 1 Bits
    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.
    找出一个uint数据当中1的个数,非常easy不分析了

    #include <stdlib.h>
    #include <stdio.h>
    
    typedef unsigned int  uint32_t;
    typedef unsigned char uchar8_t;
    
    
    int hammingWeight(uint32_t n) {
        uint32_t i = 0;
        uint32_t tem = 1;
        uint32_t r = 0;
        for(i=0;i<32;i++)
        {
            if(tem & n)
                r += 1;
            n = n >> 1; 
            if(n == 0) break;
        }
        return r;
    }
    //解法2
    int hammingWeight1(uint32_t n) 
    {
    
        uint32_t r = 0;
        while(0 != n)
        {
            r++;
            n &= (n-1);
        }
        return r;
    }
    
    
    
    int main()
    {
        uint32_t n = 0b00000000000100000000000000001011;
        int r = hammingWeight(n);
        int r1 = hammingWeight1(n);
        printf("hammingWeight n has %d  1bit
    ",r);
        printf("hammingWeight n has %d  1bit
    ",r1);
    }
    
  • 相关阅读:
    Bootstrap按钮
    Bootstrap表单
    Bootstrap表格
    Bootstrap列表
    jq 的onchange事件
    php 跳出循环的几种方式
    php变量和字符串连接符——点
    php 从2维数组组合为四维数组分析
    mysql 删除表中记录
    mysql 聚合函数
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/7002787.html
Copyright © 2011-2022 走看看