DEV Community

Ritik Rana
Ritik Rana

Posted on

JavaScript Coding Challenge #2: Add all Integer in a string using JavaScript.

Input : A single string "1bn22vg4n62"

Output : 89

Problem : Add all Integer in a string using JavaScript.



let s = '1bn22vg4n62';                //Input String
temp = "";                       //temp var to capture digit from string
sum=0;                               //sum variable to add
for(let i=0;i<s.length;i++){

  if(!isNaN(parseInt(s[i]))){    //logic to check char in string is digit
    temp+=s[i];                  //if true add char to temp string
  }
  else{
    sum+=parseInt(temp);         //if char in string is char- add to sum after 
                                 //converting into integer
    temp="0"                     //setting temp to 0 to neglect effect
  }
}
console.log(sum+parseInt(temp));  
//89

Enter fullscreen mode Exit fullscreen mode

Next Coding Challenge: updated soon

Top comments (10)

Collapse
 
kafiil profile image
Kafil

Great.
You can do this in a single line of code, but that is a little harder to read.

const result = '1bn22vg4n62'.match(/\d+/g).reduce((acc,e)=>acc+parseInt(e),0);
console.log(result) // 89
Collapse
 
giacomocerquone profile image
Giacomo Cerquone

yes I'd have done the same and no, I don't believe this is harder to read than the posted code :)

Collapse
 
ritikrana profile image
Ritik Rana

Great. That can be done. 👌👌
but they are 2 lines.😉😁✌

Collapse
 
kafiil profile image
Kafil

haha 😊

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Interesting!

This problem doesn't seem well defined, though. How do we know if the 22 in this string is really a 22 and not just two adjacent twos?

1bn22vg4n62

Or likewise, that 62 is not 6 and 2?

I think it needs to clarify that anything between other characters is treated as a single number. Otherwise it's ambiguous.

Collapse
 
ritikrana profile image
Ritik Rana

yes my bad. they have to be treated as one digit.✌✌✌

Collapse
 
kafiil profile image
Kafil

Then I should change my code to this :

console.log('1bn22vg4n62'.match(/\d/g).reduce((acc,e)=>acc+parseInt(e),0)) //17;
Thread Thread
 
ritikrana profile image
Ritik Rana

✌️😅

Collapse
 
youssefrabeiii profile image
Youssef Rabei • Edited

Where do you bet your problems.
Im doing 30 days of codewars, it like you, im making the third day post right now.
Check it out

Collapse
 
ritikrana profile image
Ritik Rana

Great Rabei . Just uploading problem that I found more interesting while solving coding problems. I code at HackerRank