专栏文章

题解:P1001 A+B Problem

P1001题解参与者 1已保存评论 0

文章操作

快速查看文章及其快照的属性,并进行相关操作。

当前评论
0 条
当前快照
1 份
快照标识符
@mipcx1xn
此快照首次捕获于
2025/12/03 09:57
3 个月前
此快照最后确认于
2025/12/03 09:57
3 个月前
查看原文
别人在大炮打蚊子,我来手搓蚊子.jpg
本文保证代码只用到逻辑运算符。

1.1位加法器

输入:两个一位 bool 数 a,ba,b,以及上一位的进位 cc
输出:这一位的结果,以及产生的进位。
过程:如果 a,b,ca,b,c 中有两个以上为 11,那么就有进位。如果 abc=1a \oplus b \oplus c=1,那么这一位就是 11
CPP
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位加法器

每一位依次计算。
CPP
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 的结果。

评论

0 条评论,欢迎与作者交流。

正在加载评论...