Advertisement
Josif_tepe

Untitled

Oct 23rd, 2021
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. bool is_A_smaller_than_B(string A, string B) {
  6.     if(A.size() < B.size()) {
  7.         return true;
  8.     }
  9.     if(A.size() > B.size()) {
  10.         return false;
  11.     }
  12.     for(int i = 0; i < (int) A.size(); i++) {
  13.         if(A[i] < B[i]) {
  14.             return true;
  15.         }
  16.         if(A[i] > B[i]) {
  17.             return false;
  18.         }
  19.     }
  20.     return false;
  21. }
  22. string subtract_big_integer(string A, string B) {
  23.     if(is_A_smaller_than_B(A, B)) {
  24.         swap(A, B);
  25.     }
  26.     int sz_a = (int)A.size() - 1;
  27.     int sz_b = (int)B.size() - 1;
  28.     int carry = 0;
  29.     string diff = "";
  30.     while(sz_a >= 0 and sz_b >= 0) {
  31.         int digit_a = (A[sz_a] - '0');
  32.         int digit_b = (B[sz_b] - '0');
  33.         int razlika = digit_a - digit_b - carry;
  34.         if(razlika < 0) {
  35.             razlika += 10;
  36.             carry = 1;
  37.         }
  38.         else {
  39.             carry = 0;
  40.         }
  41.         diff += (razlika + '0');
  42.         sz_a--;
  43.         sz_b--;
  44.     }
  45.     while(sz_a >= 0) {
  46.         int digit_a = (A[sz_a] - '0');
  47.         int razlika = digit_a - carry;
  48.         if(razlika < 0) {
  49.             carry = 1;
  50.             razlika += 10;
  51.         }
  52.         else {
  53.             carry = 0;
  54.         }
  55.         diff += (razlika + '0');
  56.     }
  57.     reverse(diff.begin(), diff.end());
  58.     return diff;
  59. }
  60. int main()
  61. {
  62.     cout << subtract_big_integer("98421", "19999") << endl;
  63.  
  64.     return 0;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement