2057
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 void reverse(string& a) 6 { 7 int len = a.size(); 8 for(int i = 0; i < len/2; ++i) 9 { 10 char t = a[i]; 11 a[i] = a[len-i-1]; 12 a[len-i-1] = t; 13 } 14 } 15 16 void exchange(string& a, int& flag1, string& b, int& flag2) 17 { 18 int flag = flag1; 19 flag1 = flag2; 20 flag2 = flag; 21 string t(a); 22 a = b; 23 b = t; 24 } 25 26 int judge(char ch) 27 { 28 if(ch == '-') 29 return -1; 30 return 1; 31 } 32 33 void f(string& a) 34 { 35 int k = 0; 36 if(a[0] == '+' || a[0] == '-') 37 k =1; 38 string s(a.begin()+k, a.end()); 39 a = s; 40 } 41 42 char f2(char& ch) 43 { 44 ch = (ch >= 'A' )? (ch-'A'+10):(ch-'0'); 45 return ch; 46 } 47 char f3(char& ch) 48 { 49 ch = (ch > 9)?(ch-10+'A'):(ch+'0'); 50 return ch; 51 } 52 int add(string& a, string& b) 53 { 54 int c = 0, i; 55 for(i = 0; i < b.size(); ++i) 56 { 57 a[i] = f2(a[i]) + f2(b[i]) + c; 58 c = a[i] / 16; 59 a[i] %= 16; 60 f3(a[i]); 61 } 62 while(i < a.size()) 63 { 64 a[i] = f2(a[i]) + c; 65 c = a[i] / 16; 66 a[i] %= 16; 67 f3(a[i]); 68 } 69 reverse(a); 70 return c; 71 } 72 int cut(string& a, string& b) 73 { 74 int c = 0, i; 75 for(i = 0; i < b.size(); ++i) 76 { 77 if(f2(a[i])+c < f2(b[i])) 78 { 79 a[i] = char(f2(a[i]) + 16 + c - f2(b[i])); 80 c = -1; 81 } 82 else 83 { 84 a[i] = char(f2(a[i]) + c - f2(b[i])); 85 c = 0; 86 } 87 f3(a[i]); 88 } 89 while(i < a.size() && c < 0) 90 { 91 if(f2(a[i]) + c < 0) 92 { 93 a[i] = char(f2(a[i]) + 16 + c); 94 c = -1; 95 } 96 else 97 { 98 a[i] = char(f2(a[i]) + c); 99 c = 0; 100 break; 101 } 102 f3(a[i]); 103 ++i; 104 } 105 reverse(a); 106 return c; 107 } 108 109 void out(string& a, int flag, int c) 110 { 111 if(flag < 0) 112 cout << '-'; 113 if(c) 114 cout << c; 115 cout << a << endl; 116 } 117 int main() 118 { 119 string a, b; 120 while(cin >> a >> b) 121 { 122 int flag1 = 1, flag2 = 1; 123 flag1=judge(a[0]); 124 flag2 = judge(b[0]); 125 f(a); 126 f(b); 127 if(a.size() < b.size()) 128 exchange(a, flag1, b, flag2); 129 else if(a.size() == b.size() && a < b) 130 exchange(a, flag1, b, flag2); 131 reverse(a); 132 reverse(b); 133 int c = 0; 134 if(flag1 * flag2 > 0) 135 c = add(a, b); 136 else 137 c = cut(a, b); 138 out(a, flag1, c); 139 } 140 return 0; 141 }
C_Style
1 #include <iostream> 2 #include <iomanip> 3 using namespace std; 4 int main() 5 { 6 __int64 a,b,c; 7 while(cin>>hex>>a>>b){ 8 c=a+b; 9 if(c<0){ 10 cout<<'-'; 11 c=-c; 12 } 13 cout<<hex<<uppercase<<c<<endl; 14 15 } 16 return 0; 17 }
C_Style
1 #include<stdio.h> 2 using namespace std; 3 int main() 4 { 5 __int64 a,b; 6 while(scanf("%I64X %I64X",&a,&b)!=EOF) 7 { 8 if(a+b<0) 9 printf("-%I64X\n",-a-b); 10 else 11 printf("%I64X\n",a+b); 12 } 13 return 0; 14 }