列表

详情


EP3. 嵌入式牛牛疑惑的变量

描述

在一个递归函数recursion中,有一个static修饰的变量m,它被初始化为0。现在该函数输入了一个数字n,牛牛在每次递归调用该函数的时候,都将m+n的值赋值给变量m,直到n为0时结束递归。于是牛牛就想知道这个m最后到底等于多少,你能帮牛牛实现这个递归函数,返回m的值吗?

示例1

输入:

10

输出:

55

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C 解法, 执行用时: 3ms, 内存消耗: 304KB, 提交时间: 2022-08-06

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int recursion(int n ) {
    // write code here
    static int m=0;
    for(;n>0;n--){
        m=m+n;
    }
    return m;
}

C 解法, 执行用时: 3ms, 内存消耗: 304KB, 提交时间: 2022-08-05

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */

int recursion(int n ) {
    static int m = 0;
    if (n != 0) {
        m += n;
        return recursion(n - 1);
    }
    return m;
}

C 解法, 执行用时: 3ms, 内存消耗: 304KB, 提交时间: 2022-08-04

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
#define N_NOT_ZERO(n) { \
    if(n != 0){         \
        m += n;         \
        recursion(--n); \
    }                   \
};
int recursion(int n ) {
    // write code here
    static int m = 0;
    N_NOT_ZERO(n);
    return m;
}

C 解法, 执行用时: 3ms, 内存消耗: 308KB, 提交时间: 2022-08-04

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int recursion(int n ) {
    // write code here
    static int m = 0;
    if(n == 0)    return m;
    recursion(n-1);
    m += n;
    return m;
}

C 解法, 执行用时: 3ms, 内存消耗: 312KB, 提交时间: 2022-08-05

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int recursion(int n ) {
    // write code here
    static int m = 0;
    if(n == 0) return m;
    recursion(n-1);
    m += n;
    return m;
    
}

上一题