Please design an algorithm that can add two integers stored in strings and return error for illegal input
Enter description:
The input is a line containing two strings, the length of which is in [1,100].
Output description:
The output is one line. The addition result is output in legal cases, and error in illegal cases.
Example 1
enter
123 123 abd 123
output
246 Error
python implementation:
import sys for i in sys.stdin.readlines(): try: print(sum(map(int,i.strip().split(' ')))) except: print("error")
C++ implementation:
#include <iostream> #include "string" using namespace std; intmain() { string s1, s2; bool f1 = false , f2 = false; int sum char t1[100], t2[100]; while(cin >> s1 >> s2) { for(int i = 0; i < s1.size(); i ++) { t1[i] = s1[i]; if(s1[i] >= '0' && s1[i] <= '9') { f1 = true; continue; } else { f1 = false; cout << "error" << endl; break; } } for(int i = 0; i < s2.size(); i ++) { t2[i] = s2[i]; if(s2[i] >= '0' && s2[i] <= '9') { f2 = true; continue; } else { cout << "Error" << endl; break; } } if(f1 && f2) { sum = atoi (t1) + atoi (t2); cout << sum << endl; } } return 0; }