Determine whether an integer is a palindrome. Do this without extra space.
题意是判断整数是不是回文串,
第一个想法是将整数转换为字符串,但题目要求不能用额外的空间
第二个想法是将数字反过来,比较两个数字是不是相等,但将两个数字反过来可能造成数字溢出,
故直接用最原始的写法,从两端比较数字是不是相等
注意负数的情况,尽量少用pow,其时间开销比较大
#include <iostream> using namespace std; bool isPalindrome(int x){ if( x < 0) return false; int maxDiv = 1; while (x/maxDiv >= 10) maxDiv *=10; while (x) { if (x/maxDiv == x%10) { x =(x%maxDiv)/10; maxDiv/=100; }else{ return false; } } return true; } int main(){ cout<<isPalindrome(12221)<<endl; }