题目:https://leetcode.cn/problems/palindrome-number/
这里是先把每个数字取出来存到int[],然后while循环两头比对数字是否相同。也可以先用itoa转换成char[]类型,再strlen看长度,最后while循环两头比对字符是否相同,也是类似的逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
#include <iostream> bool isPalindrome(int x) { if (x < 0) { std::cout << x << ": false" << std::endl; return false; } if (x < 10) { std::cout << x << ": true" << std::endl; return true; } int in = x; int num[10] = {0}; int index = 0; int i = 0; // store every number of x to an int array in the reverse order while (x >= 10) { num[index++] = x % 10; x = x / 10; } num[index] = x; // print the array std::cout << in << ": "; while (i <= index) { std::cout << num[i++] << " "; } std::cout << std::endl; // check the array is palindrome or not i = 0; while (i < index) { if (num[i++] != num[index--]) { std::cout << in << ": false" << std::endl; return false; } } std::cout << in << ": true" << std::endl; return true; } int main() { std::cout << "-------- false --------" << std::endl; isPalindrome(-12); isPalindrome(10); isPalindrome(120); isPalindrome(1112); isPalindrome(11212); isPalindrome(1021); isPalindrome(10021); isPalindrome(100021); isPalindrome(1000021); isPalindrome(10000201); isPalindrome(100002001); isPalindrome(1000020001); std::cout << "-------- true --------" << std::endl; isPalindrome(0); isPalindrome(1); isPalindrome(11); isPalindrome(101); isPalindrome(111); isPalindrome(12121); isPalindrome(21112); isPalindrome(21212); isPalindrome(100020001); return 0; } |