回文数
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
如果输入是负数:return false;
输入正数:如121, return true;
第一遍写法直接判断数字第一位和最后一位是否相等:
class Solution { public: bool isPalindrome(int x) { if(x <0) return false; int bits = 0; int t = x; while(t) { t = t / 10; bits += 1; } int left = x; int right = x; for(int i = 1; i <= bits/2; i++){ cout << int(left / pow(10, bits-i)) << "," << right %10<< endl; if ( int(left / pow(10, bits-i)) != right %10 ){ // cout << left / pow(10, bits-i) << "," << right%10 << endl; return false; } else { left -= int(left/(pow(10, bits-i))) * pow(10,bits-i); right = right /10; } } return true; } };
然后发现有更简单的代码:
class Solution { public: bool isPalindrome(int x) { if(x <0) return false; //int bits = 0; long int ret = 0; int t = x; while(t != 0) { ret = ret*10 + t%10; t = t/10; } return ret == x; } };
The Safest Way to Get what you Want is to Try and Deserve What you Want.