Search a number in string using a charCodes and one for loop that starts from the end

46 views Asked by At

I have string: const text = "I spent 1430 USD today"

I need to get the amount 1430 using the for loop from the end Forbidden: do not use parseInt, parseFloat, Number, +str, 1 * str, 1 / str, 0 + str, etcc

Limitations: 1 for loop, charCodeAt

I tried solving it and it makes sense that the numbers would be written in reverse order. How can I avoid this without using reverse (or other native methods) or additional loops \ functions ?

function searchAmount(str) {
  let amount = 0;

  for (let i = str.length - 1; i >= 0; i--) {
    const charCode = str.charCodeAt(i);

    if (charCode >= 48 && charCode <= 57) {
      amount = amount * 10 + (charCode - 48);
    }
  }
  return amount;
}

console.log(searchAmount(text));
1

There are 1 answers

3
CBroe On BEST ANSWER

You need to multiply the found digit with 10^0, 10^1, 10^2 etc., according to its "position", not the already calculated amount up to that point.

You could do that by keeping a multiplication factor, starting with 1, and multiplied by 10 every time after you added a digit:

function searchAmount(str) {
  let amount = 0,
    factor = 1;

  for (let i = str.length - 1; i >= 0; i--) {
    const charCode = str.charCodeAt(i);

    if (charCode >= 48 && charCode <= 57) {
      amount += (charCode - 48) * factor;
      factor *= 10;
    }
  }
  return amount;
}

console.log(searchAmount("I spent 1430 USD today"));