zoukankan      html  css  js  c++  java
  • 计算一个整数二进制中1的个数

    这是来自牛客网关于一个二进制的运算

    我的思路为每次和1 2 4 .....进行按位与运算就可得到二进制中1的个数

    代码如下

     1 /*
     2  * *new coder ponint to offer 11
     3  * find bit 1 num of a nunber 
     4  */
     5 
     6 #include <stdio.h>
     7 #include <stdlib.h>
     8 
     9 int find1num(int number)
    10 {
    11     int i = 1,count = 0;
    12 
    13     //while( number / i != 0 ) //if number is negtive we will count error
    14     
    15     while( i != 0 )
    16     {
    17         if( (number & i) != 0)
    18         {
    19             count++;
    20         }    
    21 
    22         i <<= 1; //i = i * 2
    23     }
    24     
    25     return count;
    26 }
    27 
    28 int main()
    29 {
    30 
    31     int number;
    32 
    33     while(1)
    34     {
    35         scanf("%d",&number);
    36         
    37         int count = find1num(number);
    38 
    39         printf("num of bit 1 is : %d
    ",count);
    40     }
    41 }

    下面是另外一个大哥的思路,可以明显的减少循环的次数。思路为每次将整数和整数-1的数做与运算这样每次将整数最右边的1变成0,这样做的次数就是整数中含有1的个数,代码如下:

     1 /*
     2  * *new coder ponint to offer 11
     3  * find bit 1 num of a nunber
     4  * time best 
     5  */
     6 
     7 #include <stdio.h>
     8 #include <stdlib.h>
     9 
    10 int find1num(int number)
    11 {
    12     int count = 0;
    13 
    14     
    15     while( number != 0 )
    16     {
    17         count++;
    18         number  = number & (number - 1); //every time do this will make the rightest 1 of number to 0 so we can do this opration the count 1 of number times
    19     }
    20     
    21     return count;
    22 }
    23 
    24 int main()
    25 {
    26 
    27     int number;
    28 
    29     while(1)
    30     {
    31         scanf("%d",&number);
    32         
    33         int count = find1num(number);
    34 
    35         printf("num of bit 1 is : %d
    ",count);
    36     }
    37 }
  • 相关阅读:
    VC获取系统时间、程序运行时间
    数学题
    最小费用流
    最大流模板
    计划
    算法竞赛入门经典 训练指南 之 图论(完全版持续更新)
    uva 11324 The Largest Clique 强连通分量求缩点构造DAG
    hdu 4288 Coder 一个很水的版本 >_<
    hoj 2939 Coin Question
    成都网络赛 1002 Control 1005 Food
  • 原文地址:https://www.cnblogs.com/daimadebanyungong/p/4917630.html
Copyright © 2011-2022 走看看