Algorithm : Sum of integers in a string

This is another tricky programming problem that people think easy. But it is not that easy unless you are a kind of genius.
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,
  1. We should identify Integers
  2. Get the value of Integer precisely. 
Here is the code implemented those functionalities in JavaScipt


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