争取每周做五个LeedCode题,定期更新,难度由简到难
Title: Palindrome Number
Description:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example:
Input: 121
Output: true
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Difficulty:
Easy
Note:
Could you solve it without converting the integer to a string?
Implement Programming Language:
C#
Answer:
我是通过求了一下长度,再通过运算对比两侧数字解决的。
看了下LeetCode的Solution,是通过把后半段翻转,然后对比两个结果是否相同,例如1221,把21换成12,然后12==12,认为相同,确实比我的解法要简单,这次就贴两个答案。
My Answer:
public static bool IsPalindrome(long x)
{
if (x < 0 ||( x%10==0 && x!=0)) return false;
int length = 1;
long y = x;
while(y/10 != 0)
{
y /= 10;
length++;
}
Console.WriteLine($"length is {length}");
for (int i = 1; i <= length/2; i++)
{
int j = length - i;
var left = x / (long)Math.Pow(10, i - 1) % 10;
var right = x / (long)Math.Pow(10, j) % 10;
Console.WriteLine($"left is {left},right is {right}");
if (left != right)
return false;
}
return true;
}
LeetCode Solution:
public static bool IsPalindrome(long x)
{
if (x < 0 || (x % 10 == 0 && x != 0))
{
return false;
}
long revertedNumber = 0;
while (x > revertedNumber)
{
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber / 10;//后半段解决12321这种奇数个数字的问题。
}
网友评论