跟着学习100天算法

425 阅读1分钟

第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!"