说一说,求一个正整数的二进制中0的个数

昨天突然看到一个算法题:一个正整数a的二进制中0的个数;

话说这是个老题了,直观的算法就每次右移一位,直到0为止;代码就省略了;

仔细想想有更好的方案么?

就是这个题可以转换成一个正整数~a的二进制中1的个数; 求1的个数这个貌似就很熟悉了吧;

int num = 0;

b = ~a;

while(b){

num++;

  b = b & (b-1);

}

是不是容易了许多呢

另外像java和python这种没有unsigned的语言要自己去转

b = ~a & 0x0ffff

时间: 2024-08-01 10:43:38

说一说,求一个正整数的二进制中0的个数的相关文章

求一个整数的二进制中1的个数

题目:输入一个整数,求该整数的二进制表达中有多少个1.例如输入10,由于其二进制表示为1010,有两个1,因此输出2. 假设该整数为i.首先i和1做与运算,判断i的最低位是不是为1.接着把1左移一位得到2,再和i做与运算,就能判断i的次高位是不是1……这样反复左移,每次都能判断i的其中一位是不是1.基于此,我们得到如下代码 int NumberOf1_Solution(int i) { int count = 0; unsigned int flag = 1; while(flag) { if(

[ACM] POJ 3252 Round Numbers (一个区间内二进制中0的个数大于等于1的个数有多少个,组合)

Round Numbers Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 8590   Accepted: 3003 Description The cows, as you know, have no fingers or thumbs and thus are unable to play Scissors, Paper, Stone' (also known as 'Rock, Paper, Scissors',

C++求一个十进制的二进制中1的个数

int oneNumInBinary(int n){ int cnt=0; while(n){ n = n&(n-1); cnt++; } return cnt; }

一个整数对应二进制中1的个数

#include <stdio.h> #include <stdlib.h> /* 4.统计一个整数对应的二进制数的1的个数. 输入一个整数(可正可负), 输出该整数的二进制包含1的个数, “ctl+ z” 结束. */ int main(){ int number; while (scanf("%d", &number) != EOF){ int num[100] = {0}; int length = 0; if (number < 0) nu

统计一个整数的二进制中1的个数

方法一: 比较暴力的方法(通过将二进制右移获得): int _Count(int x) { int cnt = 0; while(x) { cnt += x&1; x >>= 1; } return cnt; } 方法二: 通过这个数与比他小1的数相与得到:(很神奇的一个方法,手动写几个例子就可以看出来了,不过要自己想的话,还是比较费力的) int _Count(int x) { int cnt = 0; while(x) { x &= (x-1); cnt++; } retu

计算一个整数的二进制中1的个数

问题: 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

写一个参数返回二进制中1的个数

#include<stdio.h> int main()  {  int num;  int s=0,yus=0,count=0; printf("请输入一个数字:");  scanf("%d",&num);  for(s=num;s>=1;)  {  yus=s%2;  s=s/2;  if (yus==1)  {  count++;  }  }  printf("%d\n",count);  return 0;  }

剑指offer——二进制中0的个数

题目链接:输入一个整数,输出该数二进制表示中1的个数.其中负数用补码表示. 解题思路: 数字-1做与操作 1 public class Solution { 2 public int NumberOf1(int n) { 3 4 int count=0; 5 6 while(n!=0) 7 { 8 count++; 9 n = n &(n-1); 10 } 11 return count; 12 13 } 14 } 原文地址:https://www.cnblogs.com/wangyufeiai

Java之一个整数的二进制中1的个数

这是今年某公司的面试题: 一般思路是:把整数n转换成二进制字符数组,然后一个一个数: private static int helper1(int i) { char[] chs = Integer.toBinaryString(i).toCharArray(); int res = 0; for (int j = 0; j < chs.length; j++) { if (chs[j] == '1') { res++; } } return res; } 第二种方法是:将整数n与1进行与运算,