在 JavaScript 中查詢令人困惑的數字
令人困惑的數字
如果陣列中的一個數字在垂直和水平方向旋轉 180 度後變成另一個也在陣列中存在的數字,則該數字令人困惑。例如,如果我們將 6 垂直和水平旋轉 180 度,它將變成 9,反之亦然。
我們必須記住,只有 0、1、6、8、9 的旋轉才能產生有效的數字。
我們需要編寫一個 JavaScript 函式,該函式將自然數 num 作為第一個也是唯一的一個引數。該函式應首先構造一個包含 num 在內的所有自然數(直到 num)的陣列。
例如,對於 num = 5,陣列應為:
[1, 2, 3, 4, 5]
然後,該函式應該計算陣列中存在多少個令人困惑的數字,最後返回該計數。
例如:
如果輸入為:
const num = 10;
則輸出應為:
const output = 5;
因為陣列將是:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],令人困惑的數字是:
1, 6, 8, 9, 10
示例
程式碼如下:
const num = 10; const countConfusing = (num = 1) => { let count = 0; const valid = '01689'; const rotateMap = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}; const prepareRotation = num => { let res = ''; const numArr = String(num).split(''); if(numArr.some(el => !valid.includes(el))){ return false; }; numArr.map(el => { res = rotateMap[el] + res; }); return +res; }; for(let i = 1; i <= num; i++){ const rotated = prepareRotation(i); if(rotated && rotated > 0 && rotated <= num){ count++; }; }; return count; }; console.log(countConfusing(num));
輸出
控制檯輸出將為:
5
廣告