Online Compiler C

#include <stdio.h> int is2pow(int n) { if (n == 1) { return 1; } else if (n % 2 != 0) { return 0; } else { return is2pow(n / 2); } } int main() { int x; scanf("%d", &x); printf("%d", is2pow(x)); return 0; }
这段代码定义了一个递归函数 `is2pow`,用来判断一个整数 `n` 是否为 2 的幂。如果 `n` 是 2 的幂,函数返回 1,否则返回 0。主函数从输入读取一个整数,并输出判断结果。

- 你的递归逻辑基本正确,但需要思考当 `n` 为 0 时会发生什么。0 不是 2 的幂,但你的代码中 `n % 2 != 0` 条件对 0 不成立,会进入 `else` 分支递归调用 `is2pow(0 / 2)`,导致无限递归。考虑在函数开头增加对 `n <= 0` 情况的处理。
- 另外,注意 `n == 1` 是递归的终止条件,但 2 的幂也包括 1 本身(2^0),这个处理是正确的。