C
C#16mo 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
MODiX16mo 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
ero16mo ago
take a look at what Reverse() returns
ApathyErr
ApathyErrOP16mo ago
Reverse() returns:
System.Linq.Enumerable+ReverseIterator`1[System.Char]
System.Linq.Enumerable+ReverseIterator`1[System.Char]
I don't understand why
Angius
Angius16mo 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
MODiX16mo 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
Thinker16mo 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
x0rld16mo ago
I'm the only one wonder why this method take an int as parameter ?
Angius
Angius16mo ago
Well, what do the docs say?
Mayor McCheese
Mayor McCheese16mo ago
He means the user method I think
Angius
Angius16mo ago
Ah, the IsPalindrome()? No clue, seems useless
Mayor McCheese
Mayor McCheese16mo ago
Probably to prove out with a small subset of data
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