跳到正文

题解

题解:P1001 A+B Problem

RedLycoris约 5 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

别人在大炮打蚊子,我来手搓蚊子.jpg

本文保证代码只用到逻辑运算符。

1.1位加法器

输入:两个一位 bool 数 a,ba,b,以及上一位的进位 cc。

输出:这一位的结果,以及产生的进位。

过程:如果 a,b,ca,b,c 中有两个以上为 11,那么就有进位。如果 a⊕b⊕c=1a \oplus b \oplus c=1,那么这一位就是 11。

C++
pair<bool,bool> add1(bool a,bool b,bool c){
	bool d,e;
	d=(a&b)|(a&c)|(b&c);
	e=a^b^c;
	return {d,e};
}

2.32位加法器

每一位依次计算。

C++
int add2(int a,int b){
	int c=0,lst=0;
	pair<int,int>p;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<0;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<1;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<2;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<3;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<4;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<5;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<6;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<7;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<8;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<9;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<10;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<11;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<12;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<13;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<14;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<15;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<16;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<17;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<18;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<19;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<20;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<21;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<22;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<23;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<24;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<25;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<26;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<27;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<28;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<29;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<30;
	a>>=1,b>>=1;
	p=add1(a&1,b&1,lst);
	lst=p.second;
	c|=(p.first)<<31;
	a>>=1,b>>=1;
	return c;
}

综上,调用 add2(a,b)add2(a,b) 即可得到 a+ba+b 的结果。

原文