因为是int型整数,不是字符,不能用指针和数组下标分别从头尾比较。所以用除法求首位,用取余求末位,再进行比较。
#include<stdbool.h> bool isPalindrome(int x ) { if(x < 0) return false; int weight=1; while(x / weight >= 10) weight = weight * 10; //累计该数的位数:10,100,1000,10000…… int left, right; while(x > 0){ left = x / weight; //依次取最高位 right = x % 10; //依次取最低位 if(left != right) return false; //前后不等即结束 x = (x % weight) / 10; // x%weight是去掉首位,再/10是去掉末位 weight = weight / 100; //去掉两位 } return true; }