How to solve this

how to convert “1+4+5” sgtring to integer and get answer

what have you tried?

not able to figure out the same

I tried doing

t.map((c,i)=>{
    if(c=="+"){
      s=s+parseInt(t[i-1])+parseInt(t[i+1])
    }
    else if(c=="-"){
       s=s+parseInt(t[i-1])-parseInt(t[i+1])
    }
  })

you can’t use map on a string, is that your whole code?

Maybe along these lines …

let t = "1+2+3";

// 1. Split the string into an array, since map is an array method
t = t.split(''); 

// 2. Initialize s with first number
// (assuming the first character in the string is always a number)
let s = parseInt(t[0]);

t.map((c, i) => {
  if (c == "+") {

    // 3. remove redundat sum with previous number
    s = s + parseInt(t[i + 1])
  }
  else if (c == "-") {

    // 3. remove redundat sum with previous number
    s = s - parseInt(t[i + 1])
  }
})

console.log(s);

Another approach …

let str = "-1+2-3+4";
let arr = str.split(/(?=\D+)/); // split at each non-number
for (let i in arr) {
  arr[i] = parseInt(arr[i]); // convert each array element to an integer
}
let s = arr.reduce((sum, x) => sum + x); // sum everything up
2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.