Determine the number of palindromes
Given an integer x, if x is a palindrome integer, return true; otherwise, return false. The palindrome number refers to the integer that can be read in the same order (from left to right) and in reverse order (from right to left).
Input: x = 121 Output: true (1)
Algorithm idea:
1. Define two variables n and tmp, initialize n to 0 to record the inverted value, initialize tmp to the original number, and use to obtain the digit;
2. Traverse tmp from low bit to high bit, and use the lowest bit, the second lowest bit... of tmp as the highest bit, the second highest bit... of n respectively.
3. Determine whether n is the same as the original number, return 1 if they are the same, otherwise return 0.
Code:
//判断回文数( isPalindrome)
#include<stdio.h>
int isPalindrome(int x) {
//特判负数的情况
if (x < 0)
return 0;
int tmp = x;
//定义新变量记录倒转后的值
long long n = 0;
while (tmp) {
//tmp%10为当前次⾼位,作为个位数存⼊n
n = n * 10 + tmp % 10;
//删除个位数,前置位后移
tmp = tmp / 10;
}
return x == n;
}
int main()
{
printf("%d\n", isPalindrome(121));
return 0;
}