Files
freecodecamp--freecodecamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a06.md
T
wehub-resource-sync dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 11:55:53 +08:00

86 lines
1.9 KiB
Markdown

---
id: 69bc6cb30c1d112a2e110a06
title: "Challenge 249: String Math"
challengeType: 28
dashedName: challenge-249
---
# --description--
Given a string with numbers and other characters, perform math on the numbers based on the count of non-digit characters between the numbers.
- If the count of characters separating two numbers is even, use addition.
- If it's odd, use subtraction.
- Consecutive digits form a single number.
- Operations are applied left to right.
- Ignore leading and trailing characters that aren't digits.
For example, given `"3ab10c8"`, return `5`. Add 3 and 10 to get 13 because there's an even number of characters between them. Then subtract 8 from 13 because there's an odd number of characters between the result and 8.
# --hints--
`doMath("3ab10c8")` should return `5`.
```js
assert.equal(doMath("3ab10c8"), 5);
```
`doMath("6MINUS4")` should return `2`.
```js
assert.equal(doMath("6MINUS4"), 2);
```
`doMath("9plus3")` should return `12`.
```js
assert.equal(doMath("9plus3"), 12);
```
`doMath("5fkwo#10i#%.<>15P=@20!#B/25")` should return `15`.
```js
assert.equal(doMath("5fkwo#10i#%.<>15P=@20!#B/25"), 15);
```
`doMath("a.67,1$lk6ldf34@#LD@]2d32d2'2l3,@l3L#@2gh35s09if=df#$t9sm49t0df3$^%[vc;:0:4mt")` should return `67`.
```js
assert.equal(doMath("a.67,1$lk6ldf34@#LD@]2d32d2'2l3,@l3L#@2gh35s09if=df#$t9sm49t0df3$^%[vc;:0:4mt"), 67);
```
# --seed--
## --seed-contents--
```js
function doMath(str) {
return str;
}
```
# --solutions--
```js
function doMath(str) {
const tokens = str.match(/(\d+)|(\D+)/g);
let result = null;
let pendingOp = null;
for (const token of tokens) {
if (/^\d+$/.test(token)) {
if (result === null) {
result = parseInt(token);
} else {
result = pendingOp === 'add' ? result + parseInt(token) : result - parseInt(token);
}
} else {
pendingOp = token.length % 2 === 0 ? 'add' : 'subtract';
}
}
return result;
}
```