javascript - 找到一组数字的最大值(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);
}
解决方案
您的代码中有两个简单的错误。
eachchar[0] = ...
有大写错误。它应该是eachChar[0] = ...
- 您的最后一项检查是使用单个
=
而不是比较运算符,例如==
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));
推荐阅读
- html - 如何在不添加第二个垂直滚动条的情况下摆脱垂直空白和水平滚动条?
- javascript - 填充半径是否有属性或解决方法?
- javascript - JSON.parse(JSON.stringify(data)) 返回错误
- mysql - 选择 * 其中日期 1 和日期 2 的经过时间大于
- matlab - matlab:获取变量创建时间
- elasticsearch - 如何使用 ElasticSearch 前缀查询匹配我选择的最小大小的单词
- python - 了解 maplotlib 以及如何用一位数格式化 matplotlib 轴?
- python - IndexError: 超出范围
- python - 导入模块时区分大小写是否重要?
- parsing - 解析器 DCG 不是确定性的是否合适?