第一題
function solution(S) {
  const num = chkPhone(S)
  const newNum = (num !== err)? err: fmtPhone(num)
  return newNum
}
function chkPhone(S) {
  let str = ''
  const isLenShorter = S.length < 2
  if(isLenShorter) {
    str = err
  } else {
    str = S.match(/\d/g).join('')
  }
  return str
}
function fmtPhone(S) {
  S = S.replace(/\s/g, '')
  var ar = S.match(/\d{0,3}/g)
  ar.pop()
  let len = 0
  let unitSet = 3
  if(ar[ ar.length - 1].length === 1) {
    const last = ar.pop()
    const last2 = ar.pop()
    const str = last2 + last
    ar = [...ar, ...str.match(/\d{0,2}/g)]
    ar.pop()
  }
  return ar.join('-')
}
  solution('999 999 999')
  solution('999 999 999 1')
  solution('999 999 999 12')
  solution('999 999 999 123')
  solution('999 9')
  solution('9')
  solution('99')
  solution('0 - 22 1985--324')
  solution('')

  // 陣列長度
  var N = A.length;
  if (N === 0) { return -1; }
  // 二分搜尋法
  var l = 0;
  var r = N - 1;
  while(l < r) {
    // 索引 因為 Math.floor 會在 往最後位數找的時候 卡住
    // ex: 期待 m = 4, l = 3, r = 4
    // Math.floor(( 3 + 4 ) / 2) = 3
    // Math.round(( 3 + 4 ) / 2) = 4
    // 這樣才能 m 才能正常工作
    var m = Math.round((l + r) / 2);
    if (A[m] > X) {
      r = m - 1;
    } else {
      l = m;
    }
  }
  if (A[l] == X) {
    return l;
  }
  return -1;
solution([1, 2, 5, 9, 9, 10], 10)
function solution(N) {
  const str = Math.pow(11,N).toString()
  return str.match(/1/g).length
}
solution(3) // output: 2
規定時間 2:50min,但因為很緊張的關係,想的很複雜,結果在第一題就花掉了很多時間,導致後面的題目沒時間思考,不僅 第二題演算法看不懂,又因為英文不好第三題花了很多時間理解,但沒在寫 code,考卷其實沒寫完。在晚上自己重做試題的時候,才發現原來不難,但都已經過了,非常可惜。
累積經驗
可能要上網多看一下別人的題庫分享,最好是原文的,這樣才懂 two digits of the number 1331 are equal to 1. 是再說 1331 有兩個 1.
基礎演算法要懂一下,搜尋用的,排序用的,這樣看到 核心 code 的時候才會知道在幹嘛。


留言
張貼留言