首页 > 解决方案 > 找到一组数字的最大值(JS)

问题描述

我今天看到一个挑战如下:对于给定的数字 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);
 }

标签: javascriptarrayssortingfor-loopwhile-loop

解决方案


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

  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));


推荐阅读