1619C - Wrong Addition - CodeForces Solution


implementation *1200

Please click on ads to support us..

Python Code:

t = int(input())
for i in range(t):
    ans = list()
    a, s = map(str, input().split())
    j = len(a) - 1
    k = len(s) - 1
    lis = ''
    while True:
        if k < j:
            ans = [-1]
            break
        if j == -1:
            lis = s[:k + 1]
            break
        if s[k] < a[j] and k > 0:
            if s[k - 1] == '1':
                s1 = int(s[k - 1] + s[k])
                k -= 1
                ans.append(s1 - int(a[j]))
            else:
                ans = [-1]
                break
        elif s[k] < a[j] and k == 0:
            ans = [-1]
            break
        else:
            ans.append(int(s[k]) - int(a[j]))
        k -= 1
        j -= 1
    if len(lis) == 0:
        while ans[-1] == 0 and len(ans) > 1:
            ans.pop()
    ans = reversed(ans)
    for i in ans:
        lis += str(i)
    print(lis)

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define ll long long

int main(){

   int t; cin>>t;
   while(t--){
      ll a,s; cin>>a>>s;
      bool flag=true;
      ll e=1,b=0;
      while(s>0){
        ll d=a%10,f=s%10;
        s/=10,a/=10;
        ll w=10;
        if(f<d){
            f=f+w*(s%10);
            s/=10,w*=10;
        }
        if(f-d>9 || f<d){
          flag=false;
          break;
        }
        b+=e*(f-d);
        e*=10;
      }
      if(a!=0){
        flag=false;
      }
      if(flag){
        cout<<b<<endl;
      }
      else{
        cout<<-1<<endl;
      }
   }

return 0;
}


Comments

Submit
0 Comments
More Questions

796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings
677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=
450A - Jzzhu and Children
546A - Soldier and Bananas
32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation
1559A - Mocha and Math
832A - Sasha and Sticks
292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad
233A - Perfect Permutation
1360A - Minimal Square
467A - George and Accommodation