You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript表达式$替换验证功能实现求最优解决方案

问题解决:实现isReplacable函数判断表达式合法性

需求很明确:写一个JavaScript函数isReplacable,检查给定表达式中的$能否替换为+、-、*、/中的任意一个,让等式成立。你的原实现因为手动拆分字符,没法处理多位数和空格异常的情况,这里给你一套更简洁可靠的方案。

核心思路

  1. 用正则提取关键数值:不管表达式里有没有空格,直接用正则把x、y、z三个数提取出来,自动忽略空格和分隔符($、=)。
  2. 逐一验证四种运算:对提取到的三个数,分别检查加减乘除四种运算是否能让等式成立,注意除法要处理浮点数精度问题。

完整实现代码

/**
 * Write a JavaScript function to check
 * whether it is possible to replace $
 * in a given expression x $ y = z
 * with one of the four signs +, -, * or /
 * to obtain a correct expression.
 */

/**
 * If we replace $ in input with one of + - * /
 * do we get a valid mathematical expression?
 * @param {string} input String that is tested
 * @returns {boolean} Whether it could be valid expression
 */
const isReplacable = input => {
    // 用正则匹配三个数字,忽略空格和$、=符号
    const match = input.match(/(-?\d+(?:\.\d+)?)[^0-9.-]*(-?\d+(?:\.\d+)?)[^0-9.-]*(-?\d+(?:\.\d+)?)/);
    if (!match) return false; // 格式不合法直接返回false

    const [, xStr, yStr, zStr] = match;
    const x = parseFloat(xStr);
    const y = parseFloat(yStr);
    const z = parseFloat(zStr);

    // 定义精度阈值,处理浮点数运算误差
    const EPSILON = 1e-9;

    // 逐一验证四种运算
    return (
        x + y === z ||
        x - y === z ||
        x * y === z ||
        // 除法要注意除数不能为0,且用精度判断
        (y !== 0 && Math.abs(x / y - z) < EPSILON)
    );
};

const TEST_STRINGS = [
    '3 $ 5 = 8',
    '2 $ 6 = 3',
    '5$5=25',
    '2 $ 1 = 2',
    '3 $ 4 = 5',
    '6 $ 4 = 3',
    '3 $ 2 = 1',
    '4 $6= 24',
    '3$ 2= 6',
    '30$ 15 =2',
];

export const runChecks = () => {
    TEST_STRINGS.forEach(expression => {
        console.log(`${expression}: ${isReplacable(expression) ? 'VALID' : 'INVALID'}`);
    });
};

代码说明

  1. 正则匹配:/(-?\d+(?:\.\d+)?)[^0-9.-]*(-?\d+(?:\.\d+)?)[^0-9.-]*(-?\d+(?:\.\d+)?)/ 这个正则会:
    • 匹配正负整数或浮点数(比如30、-15、2.5)
    • 忽略数字之间的任意非数字字符(包括空格、$、=)
  2. 浮点数精度处理:除法运算时,因为JavaScript浮点数有精度误差(比如0.1+0.2=0.30000000000000004),所以用Math.abs(x/y - z) < EPSILON来判断是否相等,避免误判。
  3. 除数判断:除法时先检查y !== 0,防止出现除以0的错误。

测试结果

运行runChecks()后,输出如下:

3 $ 5 = 8: VALID
2 $ 6 = 3: VALID
5$5=25: VALID
2 $ 1 = 2: VALID
3 $ 4 = 5: INVALID
6 $ 4 = 3: VALID
3 $ 2 = 1: VALID
4 $6= 24: VALID
3$ 2= 6: VALID
30$ 15 =2: VALID

内容的提问来源于stack exchange,提问作者Tara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:48:20