首页 > 代码库 > Palindrome Number
Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
思路:首先,如果输入的数字为负数,判断为非回文。
求出给出的数字的位数相同的最小值,用i(i一定要声明为长整型,不然会溢出,出现超时)记录(注意此时求的时候要将i等于x的等号加上,以防i==x)
然后分别求出最高位和最低位进行比较,求最高位的方法就是使用x/i,然后x%i将最高位消除,取次高位,依次类推。取低位的方法就是先取模,然后除以1*10*10...,取倒数第一位,倒数第二位。。。
C++实现代码:
#include<iostream>using namespace std;class Solution {public: bool isPalindrome(int x) { if(x<0) return false; long long i=1; while(i<=x) { i*=10; } i=i/10; long long j=10; while(j<=i) { if(x/i!=(x%j)/(j/10)) return false; x=x%i; i/=10; j*=10; } return true; }};int main(){ Solution s; cout<<s.isPalindrome(1001)<<endl;}
运行结果:
Palindrome Number
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。