跟著學習100天演算法

花君發表於2018-08-15

第1天

1、觀察函式規律,寫出一個函式

  • accum("abcd"); // "A-Bb-Ccc-Dddd"
  • accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
  • accum("cwAt"); // "C-Ww-Aaa-Tttt
function accum(s) {
    return s.split('').map((c, i) => (c.toUpperCase() + c.toLowerCase().repeat(i))).join('-')
}
複製程式碼

知識點。 map, split touperCase toLowercase repeat join. 要用鏈式寫法

第2天

2、找出最大值和最小值

  • highAndLow("1 2 3 4 5"); // return "5 1"
  • highAndLow("1 2 -3 4 5"); // return "5 -3"
  • highAndLow("1 9 3 4 -5"); // return "9 -5"
//第一種寫法
function highAndLow(str) {
    let arr = str.split(" ");
    return `${Math.max(...arr)} ${Math.min(...arr)}`
}

//第二種寫法
function highAndLow(str) {
    let arr = str.split(" ").sort((a, b) => a - b);
    return `${arr.shift()} ${arr.pop()}`;

}
highAndLow("1 2 3 4 5");
複製程式碼

第3天

3、判斷字串中x的數量和o的數量是否相等(忽略大小寫):

  • XO("ooxx") => true
  • XO("xooxx") => false
  • XO("ooxXm") => true
  • XO("zpzpzpp") => true // 沒有x也沒有o,所有相等,都為0
  • XO("zzoo") => false
   function XO(str) {
    let s = str.toLowerCase();
    if (s.indexOf("o") < 0 || s.indexOf("x") < 0) {
        return false
    }else{
        var rex = new RegExp("x", "g");
        let reo = new RegExp("o", "g");
        return Object.is(s.match(rex).length, s.match(reo).length)
    }
}
console.log(XO("zpzpzpp")); 

// 答案1
function XO(str) {
    str = str.toLowerCase().split('')
    return str.filter(x => x === 'x').length === str.filter(x => x === 'o').length
}
console.log(XO('xxoo'))

// 答案2
function XO(str) {
    return (str.match(/x/ig) || []).length === (str.match(/o/ig) || []).length;
}
複製程式碼

第4天

4、 寫一個函式判斷一個數字是不是某個整數的平方。

  • is_square (-1) # => false
  • is_square 0 # => true
  • is_square 3 # => false
  • is_square 4 # => true
  • is_square 25 # => true
  • is_square 26 # => false
//lanhua
function is_square(num) {
    return Math.sqrt(num).toString().indexOf(".") < 0
}

console.log(is_square(3));
// 答案1
function isSquare(n) {
    return Math.sqrt(n) % 1 === 0
}

// 答案2
function isSquare(n) {
    return Number.isInteger(Math.sqrt(n))
}
// 答案3
function isSquare(n) {
    const s = Math.sqrt(n)
    return s === (s | 0)
    // return s === ( ~~s )
}
複製程式碼

第5天

5、寫一個函式,將字串除了最後的四位,其他都變成#

  • maskify("4556364607935616") == "############5616"

  • maskify( "64607935616") == "#######5616"

  • maskify( "1") == "1"

  • maskify( "") == ""

  • // "What was the name of your first pet?"

  • maskify("Skippy") == "##ippy"

  • maskify("Nananananananananananananananana Batman!") == "####################################man!"

相關文章