跳到正文

题解

题解:P1001 A+B Problem

Leathback约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年5月10日
收录
2025年12月12日
更新
2026年11月22日
篇幅
约 1 分钟
题目
P1001

版本

  1. v1当前

竟然是加法,对于 return_second 这个脑容量只有 11 毫升奶龙来说太难了吧……所以你需要帮助他。

显然,对于一只奶龙,他只会二进制,于是只需要把十进制转化为二进制,再通过模拟竖式的方法算出和,再转化为十进制就可以了。

给出代码:

C++
#include<bits/stdc++.h>
using namespace std;
int a,b;
int cnta,cntb;
int ta[35],tb[35];//二进制数组
int sum[35],ans;//答案数组及答案 
int main()
{
	scanf("%d%d",&a,&b);
	while(a)//短除法算出二进制数 
	{
		ta[++cnta]=a%2;
		a/=2;
	}
	while(b)//同理 
	{
		tb[++cntb]=b%2;
		b/=2;
	}
	int len=max(cnta,cntb);
	for(int i=1;i<=len;i++)
	{
		sum[i]+=ta[i]+tb[i];
		if(sum[i]>=2)//处理进位 
		{
			sum[i+1]+=sum[i]/2;
			sum[i]%=2;
		}
	}
	while(sum[len+1])len++;//处理位数 
	for(int i=1,cnt=1;i<=len;i++,cnt*=2)//cnt是权值
		ans+=sum[i]*cnt;
	printf("%d\n",ans); 
    return 0;
}
原文