Introduction to Algorithms:exercise2.1_4
2007-09-26 21:19
435 查看
Consider the problem of adding two n-bit binary integers, stored in two n-element arrays A
and B. The sum of the two integers should be stored in binary form in an (n + 1)-element
array C. State the problem formally and write pseudocode for adding the two integers.
My answers:
discriptions:
bitset <n> A; A[]=0 | 1;
bitset <n> B; B[] =0|1;
require:bitset<n+1> C= A+B; C[] = 0|1;
My codes in C++:
#include <iostream>
#include <bitset>
using std::cin;
using std::cout;
using std::endl;
using std::bitset;
#define N 8
int main()
...{
bitset<N+1> flag(0);
bitset<N> A;
bitset<N> B;
bitset<N+1> C;
cout << "enter two" << N << "bit binary" << endl;
cin >> A >> B;
for(int j=0; j != N; ++j)
...{
if(A[j] && B[j] && flag[j])
...{
C[j] = flag[j];
flag[j+1] = 1;
}
else if((A[j] && B[j]) || (A[j] && flag[j]) || (B[j] && flag[j]))
...{
C[j] = 0;
flag[j+1] = 1;
}
else
C[j] = A[j] + B[j] + flag[j];
}
C[j] = flag[j];
cout << C << endl;
return 0;
}
and B. The sum of the two integers should be stored in binary form in an (n + 1)-element
array C. State the problem formally and write pseudocode for adding the two integers.
My answers:
discriptions:
bitset <n> A; A[]=0 | 1;
bitset <n> B; B[] =0|1;
require:bitset<n+1> C= A+B; C[] = 0|1;
My codes in C++:
#include <iostream>
#include <bitset>
using std::cin;
using std::cout;
using std::endl;
using std::bitset;
#define N 8
int main()
...{
bitset<N+1> flag(0);
bitset<N> A;
bitset<N> B;
bitset<N+1> C;
cout << "enter two" << N << "bit binary" << endl;
cin >> A >> B;
for(int j=0; j != N; ++j)
...{
if(A[j] && B[j] && flag[j])
...{
C[j] = flag[j];
flag[j+1] = 1;
}
else if((A[j] && B[j]) || (A[j] && flag[j]) || (B[j] && flag[j]))
...{
C[j] = 0;
flag[j+1] = 1;
}
else
C[j] = A[j] + B[j] + flag[j];
}
C[j] = flag[j];
cout << C << endl;
return 0;
}
相关文章推荐
- Solution for exercise 1.1-4 in Introduction to Algorithms
- 算法导论(Introduction to Algorithms )— 第二章 算法入门 — 2.1 插入排序
- Solution for Introduction to Algorithms (3rd Edition) Exercise 26.4-2
- Solution for exercise 1.3-5 in Introduction to Algorithms
- Solution for exercise 1.2-1 in Introduction to Algorithms
- Solution for exercise 1.3-7 in Introduction to Algorithms
- exercises2.1-4 of introduction to Algorithms
- Solution for exercise 1.2-3 in Introduction to Algorithms
- Studying "Introduction to Algorithms"
- 算子分裂算法介绍(Introduction to Operator Splitting algorithms)
- 麻省理工学院《算法导论》(MIT - Introduction to Algorithms)
- introduction to algorithms sorting lesson_5 Heap sorting(堆排序)
- introduction to algorithms sorting lesson_6 Counting sort (计数排序)
- introduction to algorithms 菜鸟笔记 list
- Introduction_to_algorithms_6
- Introduction to The Design and Analysis of Algorithms (1)
- Introduction to String Searching Algorithms--Rabin-Karp and Knuth-Morris-Pratt Algorithms [翻译]
- 写在前面的话——Introduction to Algorithms Third Edition
- CLRS (Introduction to Algorithms 2nd) reanding notes 2
- Exercise 1: Introduction to Code Analysis