Analyzing the code
There are some errors in your implementation. I made the corrections and will comment below.
Console.Write("Informe um número inteiro para ser invertido: ");
string numeroDigitado = Console.ReadLine();
int numeroConvertido = Int32.Parse(numeroDigitado);
string invertido = "";
for (int i = numeroDigitado.Length; i > 0; i--) {
string letra = numeroDigitado.Substring(i - 1, 1);
invertido += letra;
}
Console.WriteLine(invertido);
First I changed the name of your variables to make it a little easier to read. This is not a rule.
Before you were receiving a string from the Console, converting to whole and then converting to string again, one of these conversions is unnecessary. You can see my changes in lines 2 and 3.
Your for
was beginning in n
, which was its input converted to integer. The correct one would be to vary by the number’s number of characters. 1235
should iterate 4 times and not 1235 times.
Another solution
An easy manipulation would be to take this integer and convert it to a character array using the method .ToCharArray()
, invert this array and go back to integer.
public int ReverseInt(int input) {
char[] vetor = input.ToString().ToCharArray();
Array.Reverse(vetor);
return Int32.Parse(new String(vetor));
}
Related: https://answall.com/q/239450/64969
– Jefferson Quesado