Description
Input
The first line of input contains an integer N, (1 <= N <= 1000), which is the number of binary addition problems that follow. Each problem appears on a single line containing two binary values separated by a single space character. The maximum length of each binary value is 80 bits (binary digits). Note: The maximum length result could be 81 bits (binary digits).
Output
For each binary addition problem, print the problem number, a space, and the binary result of the addition. Extra leading zeroes must be omitted.
Sample Input
3 1001101 10010 1001001 11001 1000111 1010110
Sample Output
1 1011111 2 1100010 3 10011101
KEY:二进制相加没什么好说的,就是要注意像0001+0002这种情况;
Source:
#include<iostream> using namespace std; int a[100]; int b[100]; int la,lb; void init() { int i; for(i=0;i<100;i++) a[i]=b[i]=0; la=lb=0; } void input() { la=lb=0; int i=0; char str[100]; cin>>str; while(str[i]!='/0') { a[++la]=str[i]-48; i++; } cin>>str; i=0; while(str[i]!='/0') { b[++lb]=str[i]-48; i++; } } void add() { int i=la,j=lb; int t; if(la>=lb) { while(j>0) { a[i]=a[i]+b[j]; i--; j--; } i=la; while(i>0) { a[i-1]+=a[i]/2; a[i]=a[i]%2; i--; } i=0; while(a[i]==0&&i<la) i++; for(;i<=la;i++) cout<<a[i]; cout<<endl; } else { while(i>0) { b[j]=a[i]+b[j]; i--; j--; } j=lb; while(j>0) { b[j-1]+=b[j]/2; b[j]=b[j]%2; j--; } j=0; while(b[j]==0&&j<lb) j++; for(;j<=lb;j++) cout<<b[j]; cout<<endl; } } int main() { // freopen("fjnu_1382.in","r",stdin); int n; cin>>n; for(int i=1;i<=n;i++) { init(); input(); cout<<i<<" "; add(); } return 0; }