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\n",ans); } return 0; }
代码引用自(u011523796) 已经AC 没有问题。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!