C
C#15mo ago
ApathyErr

❔ Why does this code always return False?

public static bool IsPalindrome(int x)
{
return x.ToString().Reverse() == x.ToString();
}
static void Main(string[] args)
{
Console.Write("Enter a number:");
int x = Convert.ToInt32(Console.ReadLine());
Console.Write(IsPalindrome(x));
}
public static bool IsPalindrome(int x)
{
return x.ToString().Reverse() == x.ToString();
}
static void Main(string[] args)
{
Console.Write("Enter a number:");
int x = Convert.ToInt32(Console.ReadLine());
Console.Write(IsPalindrome(x));
}
12 Replies
MODiX
MODiX15mo ago
ero
REPL Result: Success
int x = Convert.ToInt32("1234554321");
x.ToString().Reverse() == x.ToString()
int x = Convert.ToInt32("1234554321");
x.ToString().Reverse() == x.ToString()
Result: bool
False
False
Compile: 774.662ms | Execution: 38.325ms | React with ❌ to remove this embed.
ero
ero15mo ago
take a look at what Reverse() returns
ApathyErr
ApathyErrOP15mo ago
Reverse() returns:
System.Linq.Enumerable+ReverseIterator`1[System.Char]
System.Linq.Enumerable+ReverseIterator`1[System.Char]
I don't understand why
Angius
Angius15mo ago
A string is nothing more than a char[] And .Reverse() works on collections, and returns a collection So, under the hood, it converts the string into a char[] And returns a reversed char[]
MODiX
MODiX15mo ago
Angius
REPL Result: Success
"chair".Reverse()
"chair".Reverse()
Result: ReverseIterator<char>
[
"r",
"i",
"a",
"h",
"c"
]
[
"r",
"i",
"a",
"h",
"c"
]
Compile: 526.269ms | Execution: 46.645ms | React with ❌ to remove this embed.
Thinker
Thinker15mo ago
Reverse() does not return a string, therefore you can't compare it with a string. You have two options: - Use x.ToString().Reverse().SequenceEqual(x.ToString()) which compares whether two sequences of things (chars in this case) contain the same items. - Change approach and use a for loop to go through the string and compare each character with another at the other end of the string.
x0rld 👻 🎃
x0rld 👻 🎃15mo ago
I'm the only one wonder why this method take an int as parameter ?
Angius
Angius15mo ago
Well, what do the docs say?
Mayor McCheese
Mayor McCheese15mo ago
He means the user method I think
Angius
Angius15mo ago
Ah, the IsPalindrome()? No clue, seems useless
Mayor McCheese
Mayor McCheese15mo ago
Probably to prove out with a small subset of data
Accord
Accord15mo 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