How to write a palindrome number algorithm in the C lan…
A common algorithm in C language to check if a number is a palindrome is by converting the number into a string and checking if the string is a palindrome. Here is an example code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int isPalindrome(int num) {
char str[20];
sprintf(str, "%d", num); // 将整数转换为字符串
int len = strlen(str);
for (int i = 0; i < len/2; i++) {
if (str[i] != str[len-i-1]) {
return 0; // 不是回文数
}
}
return 1; // 是回文数
}
int main() {
int num;
printf("请输入一个整数:");
scanf("%d", &num);
if (isPalindrome(num)) {
printf("%d是回文数\n", num);
} else {
printf("%d不是回文数\n", num);
}
return 0;
}
In the code above, integers are converted to strings using the sprintf function. Then, a loop is used to traverse the first half of the string to check if it matches the corresponding second half. If any characters do not match, the number is not a palindrome. If no mismatches are found after the loop ends, then the number is a palindrome.