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
Next Coding Challenge: updated soon
Top comments (10)
Great.
You can do this in a single line of code, but that is a little harder to read.
yes I'd have done the same and no, I don't believe this is harder to read than the posted code :)
Great. That can be done. 👌👌
but they are 2 lines.😉😁✌
haha 😊
Interesting!
This problem doesn't seem well defined, though. How do we know if the
22
in this string is really a22
and not just two adjacent twos?Or likewise, that
62
is not6
and2
?I think it needs to clarify that anything between other characters is treated as a single number. Otherwise it's ambiguous.
yes my bad. they have to be treated as one digit.✌✌✌
Then I should change my code to this :
✌️😅
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
Day 00: 30 Days of Codewars.js
Youssef Rabei ・ Apr 19 ・ 1 min read
Great Rabei . Just uploading problem that I found more interesting while solving coding problems. I code at HackerRank