Advertisement
nikitta_e

Разлика на дълги числа

Jun 18th, 2018
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using  namespace  std;
  4. string FillWithZeros(int nums)
  5. {
  6.     string text = "";
  7.     for(int counter = 0; counter < nums; counter++)
  8.     {
  9.         text += "0";
  10.     }
  11.     return text;
  12. }
  13.  
  14. int main()
  15. {
  16.     string firstNum, secondNum;
  17.     cin>>firstNum;
  18.     cin>>secondNum;
  19. bool znak=false;
  20.     if (firstNum.length() > secondNum.length())
  21.     {
  22.         int diff = firstNum.length() - secondNum.length();
  23.         secondNum = FillWithZeros(diff) + secondNum;
  24.     }
  25.     else if (firstNum.length() < secondNum.length())
  26.     {
  27.         int diff = secondNum.length() - firstNum.length();
  28.         firstNum = FillWithZeros(diff) + firstNum;
  29.         swap(firstNum,secondNum);znak=true;
  30.     }
  31.     else if(firstNum<secondNum){  swap(firstNum,secondNum);znak=true;}
  32.  
  33.     string result = "";
  34.     for(int index = firstNum.length() - 1; index >= 0; index--)
  35.     {
  36.         int firstNumDigit = (int)firstNum[index] - 48;
  37.         int secondNumDigit = (int)secondNum[index] - 48;
  38.         if (firstNumDigit < secondNumDigit)
  39.         {
  40.             firstNum[index - 1]--;
  41.             firstNumDigit += 10;
  42.         }
  43.         int diff = firstNumDigit - secondNumDigit;
  44.         result = (char)(diff + 48) + result;
  45.  
  46.     }
  47.     if(znak)cout<<'-';int n=result.size();
  48.     int i=0; while(result[i]=='0'&& i<n-1 )i++;
  49.     for(; i<n; i++)cout<<result[i];
  50.  
  51. return 0;
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement