Add Two Big Numbers (String)
JavaScript
Hard
4 views
Problem Description
Two very large non-negative integers are given as strings. Add them and print the sum as string.
Input Format
Two lines: A and B.
Output Format
One line sum.
Sample Test Case
Input:
999999999999999999
2
Output:
1000000000000000001
Constraints
Length of each number up to 1e5.
Official Solution
const fs=require('fs');const lines=fs.readFileSync(0,'utf8').trim().split(/\
?\
/);const A=(lines[0]||'0').trim();const B=(lines[1]||'0').trim();let i=A.length-1,j=B.length-1,carry=0;let out=[];while(i>=0||j>=0||carry){const da=i>=0?A.charCodeAt(i--)-48:0;const db=j>=0?B.charCodeAt(j--)-48:0;let s=da+db+carry;out.push(String(s%10));carry=Math.floor(s/10);}process.stdout.write(out.reverse().join(''));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!