C For Loop: Check if Number is Palindrome

A palindrome number is a number that reads the same from left to right as it does from right to left, such as 1221 or 12321. To determine if a number is a palindrome, you can use a for loop with the following steps:

  1. Save the input number in the variable “num”.
  2. Assign the value of ‘num’ to another variable ‘temp’ for future comparison.
  3. Reverse the order of “num” and store it in the variable “reverse_num”.
  4. Loop through each position of num and reverse_num to compare if the corresponding digits are equal. If there is any inequality, it is not a palindrome number, then return false.
  5. If all digits at all positions are equal, it indicates a palindrome number, return true.

Here is a sample code:

#include <stdio.h>

int isPalindrome(int num) {
    int temp = num;
    int reverse_num = 0;
    
    // 反转数字
    while (temp > 0) {
        reverse_num = reverse_num * 10 + temp % 10;
        temp /= 10;
    }
    
    // 判断是否是回文数
    while (num > 0) {
        if (num % 10 != reverse_num % 10) {
            return 0; // 不是回文数
        }
        num /= 10;
        reverse_num /= 10;
    }
    
    return 1; // 是回文数
}

int main() {
    int num;
    printf("请输入一个数字:");
    scanf("%d", &num);
    
    if (isPalindrome(num)) {
        printf("%d 是回文数\n", num);
    } else {
        printf("%d 不是回文数\n", num);
    }
    
    return 0;
}

Using the above code, one can determine if a number is a palindrome.

bannerAds