Given an integer x, return true if x is palindrome integer.
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
An integer is a palindrome when it reads the same backward as forward.
- For example,
121is a palindrome while123is not.
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
Example 1:
Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
Example 3:
Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
解释:从右向左读, 为 01 。因此它不是一个回文数。
Constraints:提示:
-<= x <=
- 1
Follow up: Could you solve it without converting the integer to a string?
进阶:你能不将整数转为字符串来解决这个问题吗?
C语言:
bool isPalindrome(int x){
long n=x,r=0;
if(x<0) return false;
if(x==0) return true;
while(n>0)
{
r=r*10+n%10;
n=n/10;
}
return r==x;
}
执行结果:通过
执行用时:12 ms, 在所有 C 提交中击败了43.77%的用户
内存消耗:5.7 MB, 在所有 C 提交中击败了75.78%的用户
通过测试用例:11510 / 11510
不明白为什么int运行失败,只能把int改为long。
C语言:
bool isPalindrome(int x){
long n=x,r=0;
if(x<0) return false;
if(x==0) return true;
while(n>0)
{
r=r*10+n%10;
n=n/10;
}
if(r==x)
return true;
else
return false;
}
执行结果:通过
执行用时:16 ms, 在所有 C 提交中击败了20.22%的用户
内存消耗:5.8 MB, 在所有 C 提交中击败了41.38%的用户
通过测试用例:11510 / 11510
C语言:
bool isPalindrome(int x){
int i=0,j=0;
char s[11]={'\0'};
if(x<0) return false;
if(x==0) return true;
while(x>0)
{
s[i]=x%10+'0';
x=x/10;
i++;
}
i--;
while(j<i)
{
if(s[i]!=s[j]) return false;
i--;
j++;
}
return true;
}
执行结果:通过
执行用时:8 ms, 在所有 C 提交中击败了73.44%的用户
内存消耗:5.7 MB, 在所有 C 提交中击败了71.46%的用户
通过测试用例:11510 / 11510
该博客介绍了如何使用C语言判断一个整数是否为回文数。提供了三种不同的实现方法,包括利用长整型变量反转数字和使用字符数组。所有方法均通过了测试用例,其中一种方法实现了最短的执行时间。
5941

被折叠的 条评论
为什么被折叠?



