题目1513:二进制中1的个数-九度

题目描述:
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
输入:
输入可能包含多个测试样例。
对于每个输入文件,第一行输入一个整数T,代表测试样例的数量。对于每个测试样例输入为一个整数。
。n保证是int范围内的一个整数。
输出:
对应每个测试案例,
输出一个整数,代表输入的那个数中1的个数。
样例输入:
3
4
5
-1
样例输出:
1
2

32

推荐指数:※※

来源:http://ac.jobdu.com/problem.php?pid=1513

统计1的个数其实是BIT结构的核心问题。http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees

Isolating the last digit
NOTE: Instead of "the last non-zero digit," it will write only "the last digit."

There are times when we need to get just the last digit from a binary number, so we need an efficient way to do that. Let num be the integer whose last digit we want to isolate. In binary notation num can be represented as a1b, where a represents binary digits before the last digit and b represents zeroes after the last digit.

Integer -num is equal to (a1b)¯ + 1 = a¯0b¯ + 1b consists of all zeroes, so  consists of all ones. Finally we have

-num = (a1b)¯ + 1 = a¯0b¯ + 1 = a¯0(0...0)¯ + 1 = a¯0(1...1) + 1 = a¯1(0...0) = a¯1b.

Now, we can easily isolate the last digit, using bitwise operator AND (in C++, Java it is &) with num and -num:

           a1b
&      a¯1b
--------------------
= (0...0)1(0...0)


n&(-n)计算出数的最后一个1.

n-(n&(-n)),去掉最后一个1,重复上一步,过当当中记录重复次数。

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int count_ones(int n){
    int sum=0;
    while(n!=0){
        n=n-(n&(-n));
        sum++;
    }
    return sum;
}
int main()
{
    int t,n;
    scanf("%d",&t);
    for(int i=0;i<t;i++){
        scanf("%d",&n);
        printf("%d\n",count_ones(n));
    }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值