使用 C++ 中的位来添加两个无符号数字。
表示为位流的无符号数字以二进制形式写出。
54 的二进制形式是 110110。
使用位来添加两个数字,我们将使用二进制加法逻辑来添加其二进制形式。
位加法的规则是 −
- 0+0 = 0
- 1+0 = 1
- 0+1 = 1
- 1+1 = 0 加 1
我们举个例子来添加两个数字,
Input: a = 21 (10101) , b = 27 (11011) Output: 48 (110000)
说明 − 10101 + 11011 = 110000。我们将从最小有效位开始添加位。然后传播到下个位。
示例
#include <bits/stdc++.h>
#define M 32
using namespace std;
int binAdd (bitset < M > atemp, bitset < M > btemp){
bitset < M > ctemp;
for (int i = 0; i < M; i++)
ctemp[i] = 0;
int carry = 0;
for (int i = 0; i < M; i++) {
if (atemp[i] + btemp[i] == 0){
if (carry == 0)
ctemp[i] = 0;
Else {
ctemp[i] = 1;
carry = 0;
}
}
else if (atemp[i] + btemp[i] == 1){
if (carry == 0)
ctemp[i] = 1;
else{
ctemp[i] = 0;
}
}
else{
if (carry == 0){
ctemp[i] = 0;
carry = 1;
}
else{
ctemp[i] = 1;
}
}
}
return ctemp.to_ulong ();
}
int main () {
int a = 678, b = 436;
cout << "The sum of " << a << " and " << b << " is ";
bitset < M > num1 (a);
bitset < M > num2 (b);
cout << binAdd (num1, num2) << endl;
}输出
The sum of 678 and 436 is 1114
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP