C语言中,反转一个整数有多种方法。通过不同的技术手段来反转一个整数,包括基本的循环、递归、字符串操作、栈和位操作。可以根据具体需求选择合适的方法。

1、使用循环和取模运算

#include <stdio.h>

int reverseNumber(int num) {
    int reversed = 0;
    while (num != 0) {
        int digit = num % 10;
        reversed = reversed * 10 + digit;
        num /= 10;
    }
    return reversed;
}

int main() {
    int num = 12345;
    printf("Original number: %d\n", num);
    printf("Reversed number: %d\n", reverseNumber(num));
    return 0;
}

2、使用递归

#include <stdio.h>

int reverseNumberRec(int num, int reversed) {
    if (num == 0) {
        return reversed;
    }
    return reverseNumberRec(num / 10, reversed * 10 + num % 10);
}

int main() {
    int num = 12345;
    printf("Original number: %d\n", num);
    printf("Reversed number: %d\n", reverseNumberRec(num, 0));
    return 0;
}

3、使用字符串转换

#include <stdio.h>
#include <string.h>

void reverseString(char* str) {
    int n = strlen(str);
    for (int i = 0; i < n / 2; i++) {
        char temp = str[i];
        str[i] = str[n - i - 1];
        str[n - i - 1] = temp;
    }
}

int main() {
    int num = 12345;
    char str[20];
    sprintf(str, "%d", num);
    reverseString(str);
    int reversedNum = atoi(str);
    printf("Original number: %d\n", num);
    printf("Reversed number: %d\n", reversedNum);
    return 0;
}

4、使用栈

#include <stdio.h>

#define MAX 20

int stack[MAX];
int top = -1;

void push(int num) {
    if (top < MAX - 1) {
        stack[++top] = num;
    }
}

int pop() {
    if (top >= 0) {
        return stack[top--];
    }
    return -1;  // Should not reach here if used correctly
}

int reverseNumberStack(int num) {
    while (num != 0) {
        push(num % 10);
        num /= 10;
    }
    int reversed = 0;
    int multiplier = 1;
    while (top >= 0) {
        reversed += pop() * multiplier;
        multiplier *= 10;
    }
    return reversed;
}

int main() {
    int num = 12345;
    printf("Original number: %d\n", num);
    printf("Reversed number: %d\n", reverseNumberStack(num));
    return 0;
}

5、使用位操作(仅适用于无符号整数)

#include <stdio.h>

unsigned int reverseBits(unsigned int num) {
    unsigned int reversed = 0;
    while (num != 0) {
        reversed <<= 1;
        if (num & 1) {
            reversed |= 1;
        }
        num >>= 1;
    }
    return reversed;
}

unsigned int reverseNumberBitwise(unsigned int num) {
    unsigned int reversed = 0;
    while (num != 0) {
        reversed = (reversed << 3) + (reversed << 1) + (num % 10); // reversed = reversed * 10 + (num % 10);
        num /= 10;
    }
    return reversed;
}

int main() {
    unsigned int num = 12345;
    printf("Original number: %u\n", num);
    printf("Reversed number: %u\n", reverseNumberBitwise(num));
    return 0;
}

推荐文档

相关文档

大家感兴趣的内容

随机列表