我現在有一個問題正在運行:我需要一個函式來找到由引數接收到的數字中連續數字組成的最高數字。例如:如果我的輸入是 1235789,我的輸出應該是 789。如果我的輸入是 123689,??我的輸出應該是 123。
function getbiggestNumber(numberInput) {
const numberString = numberInput.toString(); // turned into string
const temporaryResult = []; // create the array of possible solutions which i'd go through to find the highest value inside of it
for (let i = 0; i < numberString.length; i = 1) {
const temporary = [numberString[i]]; // create a temporary answer that would serve as a base
for (let x = i 1; x < numberString.length; x = 1) {
const subResult = Number(numberString[i]) - Number(numberString[x]); // the result of the current number minus the following number
if (subResult === -1) { // if they are in a sequence this should be -1
temporary.push(numberString[x]); // pushing this number to that temporary answer
} // here should be some condition for it to keep running, instead getting into another number of for loop
}
temporaryResult.push(temporary); // pushing that temporary answer to the result, so I could keep track of it
}
console.log(temporaryResult); // checking the output
}
問題是這段代碼只在陣列中提供兩位數,這是我發現的唯一方法。如果有人能給我一個啟示,我會非常感激。謝謝!
uj5u.com熱心網友回復:
這看起來有點不必要的復雜。我只是根據連續數字將字串分成塊,然后呼叫Math.max所有。
const getBiggestNumber = (numberInput) => {
const digits = [...String(numberInput)].map(Number);
const chunks = [];
let lastDigit;
let chunk = [];
for (const digit of digits) {
if (lastDigit === digit - 1) {
// Continuation of sequence
chunk.push(digit);
} else {
if (chunk.length) chunks.push(chunk);
// New sequence:
chunk = [digit];
}
lastDigit = digit;
}
chunks.push(chunk);
return Math.max(
...chunks.map(chunk => Number(chunk.join('')))
);
};
console.log(getBiggestNumber(1235789));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/379773.html
標籤:javascript 算法
