Leetcode_Palindrome Number
2015-02-08 16:23
169 查看
这个问题就是判断整数是否为回文。
思路1:利用一个字符串,将int转换为字符串,但这样会需要使用额外的内存
思路2:经整数翻转,然后与原来的整数比较是否相等,但这样可能翻转后的整数会溢出
思路3:不断取整数的最高位和最低位(10进制下)进行比较,相等则取次高位和次低位进行比较
class Solution {
public:
bool isPalindrome(int x) {
if(x==0)
return true;
if(x<0)
return false;
int len=0;
int copyX=x;
while(copyX!=0)
{
++len;
copyX=copyX/10;
}
copyX=x;
for(int i=0;i<=len/2;++i)
{
if(copyX%10!=((int)(x/pow(10,(float)len-1-i))%10))
return false;
copyX=copyX/10;
}
return true;
}
};
为了规避上面程序中所用到的pow,也可以换成另外一种方式:(此源码来源于网上)
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
int d=1;
while(x/d>=10) d*=10;//d为与x位数相同的整数,即10,100,1000等
while(x>0)
{
int q=x/d;
int r=x%10;
if(q!=r) return false;
x=x%d/10;//每次比较完之后,x就去点最高位和最低位
d/=100;
}
return true;
}
};
思路1:利用一个字符串,将int转换为字符串,但这样会需要使用额外的内存
思路2:经整数翻转,然后与原来的整数比较是否相等,但这样可能翻转后的整数会溢出
思路3:不断取整数的最高位和最低位(10进制下)进行比较,相等则取次高位和次低位进行比较
class Solution {
public:
bool isPalindrome(int x) {
if(x==0)
return true;
if(x<0)
return false;
int len=0;
int copyX=x;
while(copyX!=0)
{
++len;
copyX=copyX/10;
}
copyX=x;
for(int i=0;i<=len/2;++i)
{
if(copyX%10!=((int)(x/pow(10,(float)len-1-i))%10))
return false;
copyX=copyX/10;
}
return true;
}
};
为了规避上面程序中所用到的pow,也可以换成另外一种方式:(此源码来源于网上)
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
int d=1;
while(x/d>=10) d*=10;//d为与x位数相同的整数,即10,100,1000等
while(x>0)
{
int q=x/d;
int r=x%10;
if(q!=r) return false;
x=x%d/10;//每次比较完之后,x就去点最高位和最低位
d/=100;
}
return true;
}
};
相关文章推荐
- [LeetCode] Same Tree
- LeetCode: Container With Most Water
- LeetCode N-Queens
- leetcode——Add Two Numbers 两个链表表示的正整数对其求和(AC)
- leetcode Longest Consecutive Sequence
- [LeetCode] Unique Binary Search Trees
- leetcode-3 closest
- LeetCode – Refresh – Best Time to Buy and Sell Stock iii
- [LeetCode]Count Primes
- leetcode 226 Invert Binary Tree 翻转二叉树
- leetcode--Word Break II
- Combination Sum 组合数求和-Leetcode
- LeetCode79——Word Search
- LeetCode:Find Peak Element
- leetcode 242. Valid Anagram
- LeetCode - Reverse Vowels of a String
- LeetCode-274&275.H-Index
- 【leetcode】Remove Duplicates from sorted array
- leetcode之网格从起点到终点的路径数之滚动数组
- [LeetCode] Can I Win 我能赢吗