Balance Transaction Rollback
JavaScript
Hard
4 views
Problem Description
First line balance. Next line m. Next m lines are operations: DEBIT x or CREDIT x. If any debit makes balance negative, rollback all and print ROLLBACK and original balance. Else print COMMIT and final balance.
Input Format
Line1: balance. Line2: m. Next m lines ops.
Output Format
Two lines: status and balance.
Sample Test Case
Input:
10
3
DEBIT 3
DEBIT 9
CREDIT 5
Official Solution
const fs=require('fs');const lines=fs.readFileSync(0,'utf8').trim().split(/\
?\
/);let at=0;let bal=BigInt(lines[at++].trim());const orig=bal;const m=Number(lines[at++].trim());try{for(let i=0;i<m;i++){const p=(lines[at++]||'').trim().split(/\\s+/);const op=p[0];const x=BigInt(p[1]);if(op==='DEBIT'){bal-=x;if(bal<0n)throw new Error('NEG');}else if(op==='CREDIT'){bal+=x;}else throw new Error('OP');}process.stdout.write('COMMIT\
'+String(bal));}catch(e){process.stdout.write('ROLLBACK\
'+String(orig));}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!