HDU 4588

Count The Carries

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 1538    Accepted Submission(s): 540


Problem Description
One day, Implus gets interested in binary addition and binary carry. He will transfer all decimal digits to binary digits to make the addition. Not as clever as Gauss, to make the addition from a to b, he will add them one by one from a to b in order. For example, from 1 to 3 (decimal digit), he will firstly calculate 01 (1)+10 (2), get 11,then calculate 11+11 (3),lastly 110 (binary digit), we can find that in the total process, only 2 binary carries happen. He wants to find out that quickly. Given a and b in decimal, we transfer into binary digits and use Implus's addition algorithm, how many carries are there?
 

Input
Two integers a, b(0<=a<=b<1000000000), about 100000 cases, end with EOF.
 

Output
One answer per line.
 

Sample Input
  
  
1 2 1 3 1 4 1 6
 

Sample Output
  
  
0 2 3 6
 
题意:给定两个十进制数,求二进制中,从x加到y的二进制进了多少位。

思路:把这些数字的二进制纵向罗列出来,然后一位一位的把和加起来,最终得到总的进位数。从1到x,第i位上1的总数是x左移i+1位再右移i位后得到的(在第0位上,1和0以1010101010的周期出现,并且每个周期一个1,在第1位上,1和0以11001100的周期出现,并且每个周期2个1,以此类推,则第n位上的1的个数是x/2^n*2^(n-1),即先左移n+1位,再右移n位),在这里就卡了很久。。。如果x在i位上面上是1,特殊判断一下,求一下周期以外的1的个数,这个时候的1的个数是a%(1<<k)+1。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
ll val(ll a,int k)
{
    if(a == -1) return 0;
    ll t = ((a>>(k+1))<<k);
    if(a&(1ll<<k)) t+=a%(1ll<<k)+1;
    return t;
}
int main()
{
    ll ans,carry;
    int x,y;
    while(scanf("%d%d",&x,&y)!=EOF)
    {
        ans = 0;
        carry = 0;
        for(int i = 0;i < 63;i++)
        {
            carry += val(y,i) - val(x-1,i);
            carry /= 2;
            ans += carry;
        }
        printf("%I64d\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值