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

内容分享2小时前发布
0 0 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.先定义一个普通函数:(列如这里的求和)

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

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

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

  1. 测试

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

    4.结果

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

© 版权声明

相关文章

暂无评论

none
暂无评论...