(1) 小組夥伴 Allen 是用 object 做成表格來檢查,object 的 key 一定會是 string
1 2 3 4 5 6 7 8 9 10 11 12
const digits = {} for (let i = 0; i < 10; i++) { digits[i] = i // 一開始有寫 digits[i + ""] 把 number 轉成 string } // digits = { "0": 0, "1": 1, "2": 2, ... , "9": 9 }
let result = 0 for (let i = index; i < s.length; i++) { if (digits[s[i]] !=== undefined) {// is digit result = result * 10 + digits[s[i]] } elsebreak }
(2) 聽完 Allen 講完隔天我自己寫這題的時候,是先把 digits 弄成 string 存到 array 中,然後用 if string[i] in array 來判斷 character 是否為數字
var isPalindrome = function(input) { var start = 0 var end = input.length - 1 while (start < end) { var s = input.charCodeAt(start) var e = input.charCodeAt(end) if (!isLetter(s)) { start++ continue } if (!isLetter(e)) { end-- continue } if (toLowerCase(s) !== toLowerCase(e)) { returnfalse } start++ end-- } returntrue };
String.prototype.codePointAt() & String.fromCodePoint(num1, num2, ...) for valid Unicode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 之前的寫法 var toLowerCase = function(s) { let i = 0 let newString = "" while (i < s.length) { newString += String.fromCharCode(toLowerCaseCode(s.charCodeAt(i))) i++ } return newString };