我一直在嘗試為我正在做的事情創建上面提到的功能
function expandedForm(num: number): number[] {
// ...
}
const k = expandedForm(8571);
console.log(k);
// [ 8000, 500, 70, 1 ]
在網上搜索這個只能找到回傳 數字之間帶加號的字串的函式。一些幫助將不勝感激。
uj5u.com熱心網友回復:
您可以使用余數運算子操作輸入:
function expandedForm(num: number): number[] {
const arr: number[] = [];
var x = num;
// Iterate until `x` is greater than zero
//
// For each iteration, keep track of the `i`:
// First iteration, i == 0, 10^i == 10^0 == 1
// Second iteration, i == 1, 10^i == 10^1 == 10
// Third iteration, i == 2, 10^i == 10^2 == 100
// This variable will let you know the current decimal place
for (var i = 0; x > 0; i ) {
// Get the last digit of `x` by using the remainder operator
const currentDigit = x % 10;
// Insert to the array using the previous algorithm
arr.push(Math.pow(10, i) * currentDigit);
// Remove the last digit of `x` using the floor of the division by 10
x = Math.floor(x / 10);
}
// Reverse the array
return arr.reverse();
}
const k = expandedForm(8571);
console.log(k);
或者,您可以插入到 的第一個元素arr,而無需最后將其反轉:
function expandedForm(num: number): number[] {
const arr: number[] = [];
var x = num;
for (var i = 0; x > 0; i ) {
const currentDigit = x % 10;
// Insert into the first element of `arr`
arr.splice(0, 0, Math.pow(10, i) * currentDigit);
x = Math.floor(x / 10);
}
// Just return the array
return arr;
}
const k = expandedForm(8571);
console.log(k);
uj5u.com熱心網友回復:
下次請包括您自己的嘗試并解釋它是如何失敗的。
但是由于這里已經有一個有效的答案,我將簡單地發布我的版本,這兩個版本都與上述不同。
一種方法是在數學上執行此操作,使用遞回并傳遞8571to 857、 then85和 finally 的值8,將每個 10 的冪的正確倍數添加到運行串列中。它可能看起來像這樣:
const expandedForm = (n, p = 1, d = n % 10) =>
n < 10
? [n * p]
: expandedForm ((n - d) / 10, p * 10) .concat (d * p)
console .log (expandedForm (8571))
p這是當前正在使用的十的冪,d是數字的最后一位。 p開始于1,我們10在每一步乘以。
第二種方法是轉換n為字串,將其拆分為數字,然后將每個數字映射到 10 的冪的適當倍數:
const expandedForm = (n, [... ds] = String (n)) =>
ds .map ((d, i) => d * 10 ** (ds .length - 1 - i))
console .log (expandedForm (8571))
在這兩者中,我更喜歡第一個的優雅,更數學化的一個。但兩者都可以正常作業。
請注意,這兩者都會在輸出中留下零,例如,8501yield [8000, 500, 0, 1]。這可能合適也可能不合適。如果您更愿意 get [8000, 500, 1],那么其中任何一個都很容易解決:
const expandedForm = (n, p = 1, d = n % 10) =>
n < 10
? [n * p]
: expandedForm ((n - d) / 10, p * 10) .concat (d > 0 ? d * p : [])
或者
const expandedForm = (n, [...ds] = String (n)) =>
ds .filter (d => d !== '0')
.map ((d, i) => d * 10 ** (ds.length - 1 - i))
最后兩個變體在最終零位方面的行為略有不同;如果需要,我們可以修復其中一個以匹配另一個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340398.html
標籤:javascript 打字稿 算法
上一篇:大量重復的無偏洗牌
