How to reverse an integer?

Asked

Viewed 2,216 times

6

Note 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 succeeding, you’re making an exception System.ArgumentOutOfRangeException.

  • Related: https://answall.com/q/239450/64969

3 answers

15

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

I took the opportunity to fix the problem that if typing is not valid broke the application. I also did the validation that the statement asked.

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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

If you really want to do it with string do it the right way, even if for an exercise it is not necessary:

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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

10


A solution would be to use this function 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 error because you initialized your for with the value you read and not the amount of characters to be traversed.

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

  1. Below you get n the entered value and convert to integer, to convert below again to string.
  2. You initialize your control variable FOR with the input value and not with the amount of characters that in this case is what really interests us.

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

    int n = Convert.Toint32(Console.Readline());

       string s = Convert.ToString(n);
       for (int i = n; i > 0; i--)
    

Required change 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 have changed:

  1. You were going through your FOR, the entered value, and what matters to us is the amount of characters.
  2. You were using the s variable to concatenate, but there was already the value that was being read by the substring method.
  • Perfect guy, thank you so much!

  • Thanks, just remembering that as you are working with user input, it is interesting to use a Try/Cath. To ensure that the input really is a number.

  • 2

    No, if you are working with user input, it is interesting to validate the data, exception is for exceptional cases where one expects the error should not be used try-catch, so they created better solutions than exception.

8

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));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.