输入一个数字(整数),交换两位数字,最多交换一次,输出可以得到的最大的数字,如输入:1234交换1,4后,得到4231;
function exchangeNum(num) {
let result;
if (num > 0 && Number.isInteger(num)) {
const numArr = [...num.toString()];
const startPostion = findChangePosition(numArr);
const notNeedChange = numArr.slice(0, startPostion);
const needChange = numArr.slice(startPostion);
const maxNum = findMax(needChange);
const maxIndex = needChange.lastIndexOf(maxNum);
[needChange[0], needChange[maxIndex]] = [needChange[maxIndex], needChange[0]]
result = Number(notNeedChange.concat(needChange).join(''));
}
return result;
}
function findChangePosition(numArr) {
const maxNum = findMax(numArr);
let startPosition = 0;
for (let i = 0; i < numArr.length; i++) {
startPosition = i;
if (maxNum !== numArr[i]) {
break;
}
}
return startPosition;
}
function findMax(arr) {
return Math.max.apply(null, arr).toString();
}
function findMin(arr) {
return Math.min.apply(null, arr).toString();
}
// Test data
console.log(exchangeNum(1234));
console.log(exchangeNum(4321));
console.log(exchangeNum(14234));
console.log(exchangeNum(41324));
网友评论