classSolution { public: boolisPalindrome(int x){ if(x < 0) returnfalse; int num = 0; int d = x; while(x) { if(num >= INT_MAX / 10) returnfalse; num = num * 10 + x % 10; x /= 10; } return num == d; } };
T(n) : O(logn)
每次迭代除以10,所以是logn
题解
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: boolisPalindrome(int x){ if(x < 0 || x % 10 == 0 && x != 0) returnfalse; int num = 0; while(x > num) { num = num * 10 + x % 10; x /= 10; } return num == x || num / 10 == x;; } };