美文网首页
leetcode 2. 给定一个整数n,返回一个计数器函数。此计

leetcode 2. 给定一个整数n,返回一个计数器函数。此计

作者: 米诺zuo | 来源:发表于2024-07-08 11:25 被阅读0次

    给定一个整数n,返回一个计数器函数。此计数器函数最初返回n,然后每次调用时(n、n+1、n+2等)都会比前一个值多返回1。

    Example 1:
    
    Input: 
    n = 10 
    ["call","call","call"]
    Output: [10,11,12]
    Explanation: 
    counter() = 10 // The first time counter() is called, it returns n.
    counter() = 11 // Returns 1 more than the previous time.
    counter() = 12 // Returns 1 more than the previous time.
    Example 2:
    
    Input: 
    n = -2
    ["call","call","call","call","call"]
    Output: [-2,-1,0,1,2]
    Explanation: counter() initially returns -2. Then increases after each sebsequent call.
     
    
    Constraints:
    
    -1000 <= n <= 1000
    0 <= calls.length <= 1000
    calls[i] === "call"
    

    解决

    function createCounter(n: number): () => number {
        return function() {
            return n++;        
        }
    }
    
    
    /** 
     * const counter = createCounter(10)
     * counter() // 10
     * counter() // 11
     * counter() // 12
     */
    
    

    知识点: 利用闭包(closure)来记录函数被执行的次数
    1.先定义一个普通函数:(比如这里的求和)

    image.png
    2.再在闭包中创建累加器并包裹这个函数, 并给原函数重新赋值
    image.png
    1. 测试


      image.png

      4.结果


      image.png

    相关文章

      网友评论

          本文标题:leetcode 2. 给定一个整数n,返回一个计数器函数。此计

          本文链接:https://www.haomeiwen.com/subject/nyoocjtx.html