为了账号安全,请及时绑定邮箱和手机立即绑定

找到一组数字的最大值(JS)

找到一组数字的最大值(JS)

慕莱坞森 2021-10-29 13:47:06
我今天看到了一个挑战,如下所示:对于给定的数字 X 找到与 X 具有相同数字集的最大数字。这是我尝试过的代码。它在 for 循环之后停止,它应该将数字字符串添加到数组中。*代码有注释,如果您不确定某事,请随时问我。//we give the variable a number  var num = 1263; document.write(num+ "<br>");//we turn the number into a string and store it into X var X =num.toString(); document.write(X+ "<br>");//we split the digits of the number (ie from X) var eachChar = X.split(""); document.write(eachChar+ "<br>"); //we sort the numbers in order of increasing value eachChar.sort().reverse(); document.write(eachChar+ "<br>"); //add the strings together  for (i = 0; i < eachChar.length; i++) {    eachchar[0] = eachChar[0]+eachChar[i+1]; }//it stops working from here on//turn the number back into an integer TurnBack =parseInt(eachChar[0]); if (num=TurnBack) {    document.write("the initial value is the highest value"); }else{     document.write("the biggest possible value is"+ TurnBack); }
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

您的代码中有两个简单的错误。

  1. eachchar[0] = ...有大写错别字。它应该是eachChar[0] = ...

  2. 您的最后一次检查使用的是单个=而不是像==or之类的比较运算符===。应该是if (num === turnBack),否则您正在设置的值num,而不是比较它。

考虑到这一点,肯定有更简单(或至少更简洁)的方式来写这个。您的逻辑是合理的,但您可以通过将您的方法链接在一起来稍微清理一下。此外,您正在遍历数组以重建字符串,但有一个内置方法:Array.join()

const checkHighestNumber = num => {

  const highest = parseInt(num.toString().split('').sort().reverse().join(""));

  return highest === num

    ? `Initial value is the highest value.`

    : `The largest possible number from ${num} is ${highest}`;

}


console.log(checkHighestNumber(54321));

console.log(checkHighestNumber(12431));


查看完整回答
反对 回复 2021-10-29
  • 1 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信