This example was a recent asked question by Microsoft during an interview.
I got this exercise from the today daily techseries.dev :
"You are given two linked-lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list."
My favourite language is Javascript so i decided to share with you this little exercise directly in your browser.
The given example was :
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Here is the JS code to solve it :
const INPUT = "(2 -> 4 -> 3) + (5 -> 6 -> 4)"
// The replaceAll function is not yet available everywhere
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement)
}
// Clarify the input to make a simple object
const clairify = (input) => {
const parseAndReverse = (str) => {
return parseInt(str.split('').reverse().join(''))
}
input = input.replaceAll(' ', '')
input = input.replaceAll('->', '')
const data = input.match(RegExp(/([^(.)$])+/g))
const operands = [parseAndReverse(data[0]), parseAndReverse(data[2])]
const operator = data[1]
return { operands, operator }
}
// Calculate the operation
const calculate = {
// Only the first line is necessary for the exercice
'+': (o)=>{ return o[0] + o[1] },
'-': (o)=>{ return o[0] - o[1] },
'*': (o)=>{ return o[0] * o[1] },
'x': (o)=>{ return o[0] * o[1] },
'/': (o)=>{ return o[0] / o[1] }
}
// Format the result
const format = (input) => {
input = input.toString().split('').reverse()
const data = input.map((n, i) => i < input.length-1 ? `${n} ${'-> '}` : `${n}`)
return data.join('')
}
const operation = clairify(INPUT)
const answer = calculate[operation.operator](operation.operands)
console.log(format(answer))
You can try this code here :