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

CodeWar字符串递增函数逻辑异常,请求排查错误原因

求助:incrementString函数逻辑错误排查

我在做CodeWar的一道字符串递增题,自认为思路没问题,但写的incrementString函数逻辑异常,希望有人帮忙指出错误位置。

题目要求

  • 编写函数生成递增后的新字符串:
    • 若字符串以数字结尾,将末尾数字加1
    • 若字符串不以数字结尾,在字符串末尾追加数字1

示例

  • foo → foo1
  • foobar23 → foobar24

我的代码

function incrementString (strng) {
  let numbs = ["1","2","3","4","5","6","7","8","9"];
  let holdingPen = [];
  let pigPen = [];  
  //turn string into array
  strng = strng.split("")
  
  //use a for loop to find all the numbers
  for (let i = 0; i < strng.length; i++){
      //put the numbers into a holding pen
    if (strng[i] == numbs || strng[i] == "0"){
      holdingPen.push(strng[i]);
      //remove numbers from string
      strng.splice(i, 1);
    }
  }
  
  for (let j = 0; j < holdingPen.length; j++){
      //if index of 0 is before index of 123456789
  if (holdingPen.indexOf(0) < numbs.indexOf(strng[j])) {
      //push numbers to pigPen where they will hangout until everything is joined together
      pigPen.push(holdingPen[j])
      holdingPen.splice(j, 1);
    }
  }
    
  //join holdingPen and parseInt
  holdingPen = parseInt(holdingPen.join(''))
  
  //add 1
  //make newNum into an array
  let newNum = holdingPen + 1
  
  newNum = newNum.toString().split("")
  
  
  //see if the integer length increased by 1, if yes subract a 0 if there was any before it
if (newNum.length > holdingPen.toString().length) {
    pigPen.shift()
  }
    
  //join strng and holdingPen
  let result = strng.concat(pigPen, newNum)
  
  return result.join('').toString()
  
 
}

主要逻辑错误点

  1. 数字判断完全失效
    你用strng[i] == numbs判断字符是否为1-9的数字,但numbs是数组,单个字符和数组用==比较永远为false,导致只有"0"能被识别进holdingPen,1-9的数字全被漏掉。

  2. 遍历数组时的索引错乱
    第一个for循环里,每次splice(i,1)删除当前元素后,数组长度变短,但i仍在递增,会跳过下一个元素。比如原数组是['f','o','o','2','3'],删除索引3的'2'后,数组变成['f','o','o','3'],i递增到4,直接超出数组长度,'3'就被漏掉了。

  3. 前导零处理逻辑完全错误
    第二个for循环的条件holdingPen.indexOf(0) < numbs.indexOf(strng[j])问题百出:

    • holdingPen里存的是字符串形式的数字(比如"0"),indexOf(0)找的是数字0的索引,永远返回-1;
    • 此时strng已经被处理成非数字的字符数组,strng[j]是字母,在numbs里找不到,返回-1;
      整个条件永远不成立,pigPen永远是空的,前导零完全没被处理。
  4. 无数字场景处理崩溃
    如果原字符串没有数字,holdingPen是空数组,parseInt(holdingPen.join(''))会得到NaN,NaN + 1还是NaN,后续转字符串、分割数组全出错,无法生成xxx1的正确结果。

  5. 前导零的增减逻辑漏洞
    就算前面逻辑正常,pigPen.shift()的触发条件只判断数字长度是否增加,但没考虑原数字全是零的情况,比如foo0000应该变成foo0001,你的逻辑会错误地移除前导零。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:47:34