用C语言编写一个程序用递归算法将一个整数n转换成相应的字符串。例如输入483,应输出字符串“483”,n的位数不确定,可以是任意位数的整数。
时间: 2024-10-27 14:08:36 浏览: 11
一些C语言中字符串的算法问题解决实例小结
在C语言中,你可以通过递归的方式将整数转换成字符串。这里是一个基本的实现思路,使用了栈来存储每一位的值,然后逐个取出并拼接成字符串。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 函数声明,用于保存每一位的值
typedef struct {
int digit;
char is_negative;
} StackElement;
// 创建一个栈结构体
struct Stack {
StackElement *top;
int size;
};
// 初始化栈
Stack* create_stack() {
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
stack->size = 0;
return stack;
}
// 清理栈并释放内存
void destroy_stack(Stack *stack) {
free(stack->top);
free(stack);
}
// 向栈顶添加元素
void push(Stack *stack, int digit, bool is_negative) {
StackElement *new_top = (StackElement*)malloc(sizeof(StackElement));
new_top->digit = digit;
new_top->is_negative = is_negative;
new_top->next = stack->top;
stack->top = new_top;
stack->size++;
}
// 从栈顶移除并返回元素
StackElement* pop(Stack *stack) {
StackElement *temp = stack->top;
if (stack->top != NULL) {
stack->top = temp->next;
stack->size--;
free(temp);
}
return stack->top;
}
// 转换整数为字符串
char* convert_int_to_str(int n) {
Stack *stack = create_stack();
bool negative = false;
if (n < 0) {
negative = true;
n = -n;
}
while (n > 0) {
push(stack, n % 10, negative);
n /= 10;
}
char* str = (char*)malloc((stack->size + 1) * sizeof(char)); // +1 for null terminator
if (negative) {
str[0] = '-';
stack->size++; // account for the negative sign
}
while (stack->top != NULL) {
str[stack->size] = stack->top->digit + '0'; // add ASCII value of digits to string
stack->size++;
stack->top = pop(stack);
}
str[stack->size] = '\0';
return str;
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
char* str = convert_int_to_str(num);
printf("Converted string: %s\n", str);
destroy_stack(&stack); // Remember to clean up after use
free(str);
return 0;
}
```
阅读全文