In string "I spent 2 years and 11 months in Japan" there are two integers, 2 and 11. So some of integers in that string is 13.
In order to calculate the sum correctly,
- We should identify Integers
- Get the value of Integer precisely.
function sumUpNumbers(inputString) {
var answer = 0, currentNumber = 0;
for (var i = 0; i < inputString.length; i++) {
if ('0' <= inputString[i] && inputString[i] <= '9') {
currentNumber = currentNumber * 10 + inputString.charCodeAt(i) - '0'.charCodeAt(0);
}
else {
answer += currentNumber;
currentNumber = 0;
}
}
answer += currentNumber ;
return answer;
}
Feel free to add any comment and your ideas about this solutiion

No comments:
Post a Comment