当我们使用Python时,我们可以使用print("1"*n)多次打印相同的字符串。这有助于减少执行时间。如果我们有一个用 C 语言实现这一点的方法,那将会很有帮助。
预期结果是O(n)的时间复杂度
是的,您可以使用递归来打印“1”n 次。
#include <stdio.h>
void printOne(int n) {
// Base case: if n is 0, stop recursion
if (n == 0)
return;
// Print 1
printf("1 ");
// Recursively call printOne with n-1
printOne(n - 1);
}
int main() {
int n;
// Get input from the user
printf("Enter the number of times to print 1: ");
scanf("%d", &n);
// Call the recursive function
printOne(n);
return 0;
}