WA了很多次,原因是没注意答案是0的情况。
ps:刚开始想试试stl的bitset类,结果失败而终
#include <iostream> #include <string> #include <cstring> using namespace std; int main() { int n; cin >> n; for(int i = 0; i < n; i++) { string ans = ""; string s1, s2; cin >> s1 >> s2; int l1 = s1.size() - 1; int l2 = s2.size() - 1; int carry = 0; for(;l1 >= 0 || l2 >= 0 || carry == 1; l1--, l2--) { if(l1 >= 0) carry += s1[l1] - '0'; if(l2 >= 0) carry += s2[l2] - '0'; char cur = carry % 2 + '0'; ans = cur + ans; carry /= 2; } int j = 0; for(; j < ans.size(); j++) if(ans[j] == '1') break; ans.erase(0, j); cout << i + 1 << " "; if(ans.size() == 0) cout << 0; else cout << ans; cout << endl; } return 0; } //char dataA[100]; //char dataB[100]; //int numA[100]; //int numB[100]; //int ans[100]; // //int main() { // int n; // cin >> n; // for(int i = 0; i < n; i++) { // memset(dataA, '/0', sizeof(dataA)); // memset(dataB, '/0', sizeof(dataB)); // memset(numA, 0, sizeof(numA)); // memset(numB, 0, sizeof(numB)); // memset(ans, 0, sizeof(ans)); // cin >> dataA >> dataB; // int lenA = strlen(dataA); // int lenB = strlen(dataB); // int j; // for(j = lenA - 1; j >= 0; j--) numA[lenA - 1 - j] = dataA[j] - '0'; // for(j = lenB - 1; j >= 0; j--) numB[lenB - 1 - j] = dataB[j] - '0'; // for(j = 0; j < lenA || j < lenB; j++) { // ans[j] += numA[j] + numB[j]; // ans[j + 1] += ans[j] / 2; // ans[j] %= 2; // } // for(; j >= 0; j--) if(ans[j] == 1) break; // cout << i + 1 << " "; // if(j == -1) cout << 0; // for(; j >= 0; j--) // cout << ans[j]; // cout << endl; // } // return 0; //}