#include <iostream> #include <string> #include <algorithm> using namespace std; char addLetters(char a, char b) { return (char) ((a - '0' + b - '0')%10 + '0'); } char isOver(char a, char b, char over) { return (a - '0' + b - '0' + over - '0' >= 10) ? '1' : '0'; } char getChar(string s, int index) { if(index < 0) { return '0'; } return s[index]; } int main() { string shorterNumber, longerNumber, temp; cin >> shorterNumber >> longerNumber; if(shorterNumber.size() > longerNumber.size()) { temp = shorterNumber; shorterNumber = longerNumber; longerNumber = temp; } int shorterIndex = (int) shorterNumber.size() - 1; int longerIndex = (int) longerNumber.size() - 1; string result; char over = '0'; for(int i = 0; i < longerNumber.size(); i++) { result.push_back(addLetters(addLetters(getChar(shorterNumber, shorterIndex), getChar(longerNumber, longerIndex)), over)); over = isOver(getChar(shorterNumber, shorterIndex), getChar(longerNumber, longerIndex), over); shorterIndex--; longerIndex--; } if(over != '0') { result.push_back(over); } reverse(result.begin(), result.end()); cout << result << "\n"; return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include <iostream> #include <string> #include <algorithm> using namespace std; char addLetters(char a, char b) { return (char) ((a - '0' + b - '0')%10 + '0'); } char isOver(char a, char b, char over) { return (a - '0' + b - '0' + over - '0' >= 10) ? '1' : '0'; } char getChar(string s, int index) { if(index < 0) { return '0'; } return s[index]; } int main() { string shorterNumber, longerNumber, temp; cin >> shorterNumber >> longerNumber; if(shorterNumber.size() > longerNumber.size()) { temp = shorterNumber; shorterNumber = longerNumber; longerNumber = temp; } int shorterIndex = (int) shorterNumber.size() - 1; int longerIndex = (int) longerNumber.size() - 1; string result; char over = '0'; for(int i = 0; i < longerNumber.size(); i++) { result.push_back(addLetters(addLetters(getChar(shorterNumber, shorterIndex), getChar(longerNumber, longerIndex)), over)); over = isOver(getChar(shorterNumber, shorterIndex), getChar(longerNumber, longerIndex), over); shorterIndex--; longerIndex--; } if(over != '0') { result.push_back(over); } reverse(result.begin(), result.end()); cout << result << "\n"; return 0; } |