Untitled
unknown
plain_text
7 months ago
1.6 kB
1
Indexable
Never
#include <iostream> #include <algorithm> using namespace std; bool isSmaller(string str1, string str2) { int n1 = str1.length(), n2 = str2.length(); if (n1 != n2) return n1 < n2; for (int i = 0; i < n1; i++) { if (str1[i] < str2[i]) return true; else if (str1[i] > str2[i]) return false; } return false; } string findDiff(string str1, string str2) { bool negative = false; if (isSmaller(str1, str2)) { swap(str1, str2); negative = true; } string result = ""; int n1 = str1.length(), n2 = str2.length(); reverse(str1.begin(), str1.end()); reverse(str2.begin(), str2.end()); int carry = 0; for (int i = 0; i < n2; i++) { int sub = ((str1[i] - '0') - (str2[i] - '0') - carry); if (sub < 0) { sub += 10; carry = 1; } else carry = 0; result.push_back(sub + '0'); } for (int i = n2; i < n1; i++) { int sub = ((str1[i] - '0') - carry); if (sub < 0) { sub += 10; carry = 1; } else carry = 0; result.push_back(sub + '0'); } while (!result.empty() && result.back() == '0') result.pop_back(); reverse(result.begin(), result.end()); if (negative) result = '-' + result; return result; } int main() { string str1, str2; cout << "Enter the first number: "; cin >> str1; cout << "Enter the second number: "; cin >> str2; cout << "Difference: " << findDiff(str1, str2) << endl; return 0; }
Leave a Comment