How to invert an integer?

7

Notice this statement:

/*
 * Faça um programa que peça um numero inteiro positivo e em seguida mostre
 * este numero invertido. Exemplo:
 *  o 12376489 
 *      => 98467321
 *      
 */

Console.Write("Informe um número inteiro para ser invertido: ");
int n = Convert.ToInt32(Console.ReadLine());
string s = Convert.ToString(n);

for (int i = n; i > 0; i--) {
  string a = s.Substring(i - 1, 1);
  s += a;
}
Console.WriteLine(s);

I'm not getting it, you're throwing a System.ArgumentOutOfRangeException exception.

    
asked by anonymous 01.10.2017 / 20:55

3 answers

10

One solution would be to use this function that I created:

 public static void Inverter(int numero)
        {

            string valor = numero.ToString();
            string resultado = "";
            for(int i = valor.Length; i >0; i--)
            {
                resultado += valor[i-1];
            }


            Console.WriteLine(valor);
        }
Note: Your code is giving you an error because you have initialized your for with the value you read and not the number of characters to be traversed.

In this case the value 123 for example would try to execute 123 times in its for, while we have only 3 characters, which caused in its error: ArgumentOutOfRangeException

  • Below you get n in the value typed and Convert to integer, to convert down to string again.
  • You initialize the control variable of your FOR with the input value and not the amount of characters that in the case is what really interests us.

    In that part : You initialize n with the value entered, just below in your for, you scroll to the value you entered instead of the amount of characters that is what interests us in that case.

    int n = Convert.ToInt32 (Console.ReadLine ());

       string s = Convert.ToString(n);
       for (int i = n; i > 0; i--)
    
  • Change needed in your code:

    Console.Write("Informe um número inteiro para ser invertido: ");
            int n = Convert.ToInt32(Console.ReadLine());
            string s = Convert.ToString(n);
            string resultado = "";
    
            for (int i = n.ToString().Length; i > 0; i--)
            {
                string a = s.Substring(i - 1, 1);
                resultado += a;
            }
            Console.WriteLine(resultado);
    

    Points I've changed:

  • You were going through your FOR, the value entered, and what matters is the amount of characters.
  • You were using the variable s to concatenate, but there was already the value that was being read by the substring method.
  • 01.10.2017 / 21:01
    14

    Usually these exercises are to demonstrate the ability to assemble the best algorithm, and not go the easy way, so I would do mathematically.

    I have taken care of fixing the problem so that if the typing is not valid, it will break the application. I also did the validation that the statement requested.

    using static System.Console;
    
    public class Program {
        public static void Main() {
            Write("Informe um número inteiro para ser invertido: ");
            if (!int.TryParse(ReadLine(), out var numero) && numero >= 0) return;
            var invertido = 0;
            while (numero > 0) {
               invertido = invertido * 10 + numero % 10;
               numero /= 10;
            }
            WriteLine(invertido);
        }
    }
    

    See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

    If you really want to do with string do it the right way, for an exercise you do not need:

    using static System.Console;
    using System.Text;
    
    public class Program {
        public static void Main() {
            Write("Informe um número inteiro para ser invertido: ");
            var texto = ReadLine();
            if (!int.TryParse(texto, out var numero) && numero >= 0) return;
            var invertido = new StringBuilder(texto.Length);
            for(int i = texto.Length - 1; i >= 0; i--) invertido.Append(texto[i]);
            WriteLine(invertido);
        }
    }
    

    See running on .NET Fiddle . Also I put GitHub for future reference .

        
    02.10.2017 / 13:00
    8

    Analyzing the code

    There are some errors in your implementation. I made the corrections and I 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 getting a string from the Console, converting it to integer and then converting to string again, one of those conversions is unnecessary. You can see my changes on lines 2 and 3.

    Your for was starting at n , which was your integer converted. The correct would be to vary by the number of characters of the number. 1235 must iterate 4 times, not 1235 times.

    Another solution

    An easy manipulation would be to take this integer and convert it to a vector of characters using the .ToCharArray() method, invert this array and return to integer.

    public int ReverseInt(int input) {
        char[] vetor = input.ToString().ToCharArray();
        Array.Reverse(vetor);
        return Int32.Parse(new String(vetor));
    }
    
        
    01.10.2017 / 21:08