C
C#16mo ago
Kalam

❔ Palindrome

So I tried to solve this problem, and I know I've done it right.. but I must be tripping because a char array which has the same value as another char array, returns false when I try to do the .Equals method
4 Replies
Kalam
KalamOP16mo ago
C#
C#
public static void Main(string[] args)
{
Console.WriteLine(IsPalindrome(121));
}
private static bool IsPalindrome(int x)
{
var input = (x + "").ToCharArray();
return input.Equals(Reverse(input));
}

private static char[] Reverse(char[] input)
{
char[] output = new char[input.Length];
int index = 0;
for (int i = input.Length - 1; i >= 0; i--)
{
output[index] = input[i];
index++;
}
return output;
}
C#
C#
public static void Main(string[] args)
{
Console.WriteLine(IsPalindrome(121));
}
private static bool IsPalindrome(int x)
{
var input = (x + "").ToCharArray();
return input.Equals(Reverse(input));
}

private static char[] Reverse(char[] input)
{
char[] output = new char[input.Length];
int index = 0;
for (int i = input.Length - 1; i >= 0; i--)
{
output[index] = input[i];
index++;
}
return output;
}
:') I see should I use == instead? then convert em to string? me thinking it'd be the same as java :') ayt ty, I'll try the loop thing oh true i'll try that yeah, I appreciate the help :) I like efficient methods, n yours seems to be better so I'll try it out
Kalam
KalamOP16mo ago
hehe works thank you
Servator
Servator16mo ago
why not Range operator ? :/
public static bool IsPalindrome(this string text)
{
for (var i = 0; i < text.Length; i++)
{
if (text[i] != text[^(text.Length - i)])
{
return false;
}
}

return true;
}
public static bool IsPalindrome(this string text)
{
for (var i = 0; i < text.Length; i++)
{
if (text[i] != text[^(text.Length - i)])
{
return false;
}
}

return true;
}
which is
public static bool IsPalindrome(this string text) => !text.Where((t, i) => t != text[^(text.Length - i)]).Any();
public static bool IsPalindrome(this string text) => !text.Where((t, i) => t != text[^(text.Length - i)]).Any();
oh mb it should be i+1 like you said 😄 Aren't we comparing 2 indexes ? ¯\_(ツ)_/¯
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server