• HDU 4588 Count The Carries


    Count TheCarries

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


    Problem Description

    One day, Implusgets interested in binary addition and binary carry. He will transfer alldecimal 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 inorder. For example, from 1 to 3 (decimal digit), he will firstly calculate 01(1)+10 (2), get 11,then calculate11+11 (3),lastly 110 (binarydigit), we can find that in the total process, only 2 binary carries happen. Hewants to find out that quickly. Given a and b in decimal, we transfer intobinary digits and use Implus's addition algorithm, how many carries are there?

     

     

    Input

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

     

     

    Output

    One answer perline.

     

     

    Sample Input

    1 2

    1 3

    1 4

    1 6

     

     

    Sample Output

    0

    2

    3

    6

    看了半天也不知道怎么解。写了很久发现自己发明的算法超时,根本算不出来。

    看了 别人写的题解,这才懂了。

    比如1 + 2 + 3 + 4:

        1

      10

      11

    100

    ——

    122

    把各位的1的数目统计出来,和十进制一样计算,二进制可以存进int  num[70]数组中,从num[0]往num[69]算,也就是从低位往高位算。

    然后对122进行进位,122>130>210>1010  算的过程中整除2得到进位的次数,并且加到前一位,如此循环。

    #include <stdio.h>
    #include <algorithm>
    #include <iostream>
    #include <string.h>
    using namespace std;
    
    __int64 num1[70],num2[70];
    
    void calc(__int64 num[],__int64 n){
        int tmp=1;
        for(int i=0;i<63;i++)
            num[i]=0;
        for(int i=0;i<63;i++){
            if(n<=0) break;
            tmp*=2;
            num[i]=(n-n%tmp)/2;
            if(n%tmp>=tmp/2)
                num[i]+=tmp/2;
            else
                num[i]+=n%tmp;
            n=n-tmp/2;
        }
    }
    
    int main(){
        __int64 a,b;
        while(~scanf("%I64d %I64d",&a,&b)){
            __int64 ans=0;
            calc(num1,a-1);
            calc(num2,b);
            for(int i=0;i<63;i++)
                num2[i]=num2[i]-num1[i];
            for(int i=0;i<62;i++){
                ans+=num2[i]/2;
                num2[i+1]+=num2[i]/2;
            }
            printf("%I64d
    ",ans);
        }
        return 0;
    }


    代码引用自(u011523796)    已经AC 没有问题。

  • 相关阅读:
    第8.13节 Python类中内置方法__repr__详解
    Python中splitlines方法判断文本中一行结束除了回车换行符是否还有其他字符?
    Python中使用eval执行下面函数的结果怎么是字符串'10020'?
    第8.12节 Python类中使用__dict__定义实例变量和方法
    ThinkPHP---thinkphp拓展之空操作
    ThinkPHP---TP功能类之邮件
    ThinkPHP---案例--实现知识管理功能
    ThinkPHP---TP功能类之公文管理功能2----------继续完善
    ThinkPHP---TP拓展之获取IP信息
    ThinkPHP---layer插件
  • 原文地址:https://www.cnblogs.com/slankka/p/9158617.html
Copyright © 2020-2023  润新知