zoukankan      html  css  js  c++  java
  • C Count The Carries(2013南京邀请赛C题)

    C - Count The Carries

    时间限制: 3000 Ms
    内存限制: 65535 Kb

    问题描述

    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?

    输入说明

    About 100000 cases, end with EOF.

    Two integers a, b(0<=a<=b<1000000000).

    输出说明

    For each case, print one integers representing the number of carries per line.

    输入样例

    1 2
    1 3
    1 4
    1 6
    

    输出样例

    0
    2
    3
    6
    


    这题其实很水。
    只要统计a-b每一位二进制上有多少个1就好。
    比赛时候想了好久才想到==。。。

    统计1的个数安装规律统计就好了


    #include <stdio.h>
    #include <algorithm>
    #include <iostream>
    #include <string.h>
    using namespace std;
    
    void calc(int num[],int n)//计算0~n所以数中累加的各位二进制1的个数
    {
        for(int i=0;i<63;i++)num[i]=0;
        int tmp=1;
        n++;
        for(int i=0;i<63;i++)
        {
            if(tmp>n)break;
            tmp*=2;
            num[i]+=(n-n%tmp)/2;
            if(n%tmp > tmp/2)num[i]+=n%tmp-tmp/2;
        }
    }
    int num1[70],num2[70];
    int main()
    {
        int a,b;
        while(scanf("%d%d",&a,&b)==2)
        {
            calc(num1,a-1);
            calc(num2,b);
            for(int i=0;i<63;i++)num2[i]-=num1[i];
            long long ans=0;
            for(int i=0;i<63;i++)
            {
                ans+=num2[i]/2;
                num2[i+1]+=num2[i]/2;
            }
            printf("%lld\n",ans);
        }
        return 0;
    }

    注意结果用long long





    人一我百!人十我万!永不放弃~~~怀着自信的心,去追逐梦想
  • 相关阅读:
    JavaScript Json对象和Json对象字符串的关系 jsonObj<->JsonString
    VS2012 MVC4 学习笔记-概览
    java中运算符的解析和计算
    Python基本数据类型之tuple
    Python基本数据类型之list
    Python基本数据类型之str
    Python基本数据类型之int
    range和xrange梳理
    python编码
    ubuntu下的ssh
  • 原文地址:https://www.cnblogs.com/kuangbin/p/3082786.html
Copyright © 2011-2022 走看看