Skip to content

Instantly share code, notes, and snippets.

@jorgeacetozi
Last active January 1, 2022 13:47
Show Gist options
  • Save jorgeacetozi/cff7c5654a1e0da55556fb1802426f69 to your computer and use it in GitHub Desktop.
Save jorgeacetozi/cff7c5654a1e0da55556fb1802426f69 to your computer and use it in GitHub Desktop.
Reverse Integer (leetcode)
  • No Java, um int tem 32 bits, mas o bit mais representativo é reservado para o sinal. Isto significa que os números que podemos representar variam de -2^31 (-2.147.483.648) a 2^31-1 (2.147.483.647)

  • Se vc usar o método Integer.parseInt(str) passando uma String maior que 2^31-1, uma NumberFormatException será lançada

  • Se vc usar o método Integer.parseUnsignedInt(str) passando uma String maior que 2^32-1, uma NumberFormatException será lançada (porque excede o número máximo que um unsigned int suporta)

  • Se vc usar o método Integer.parseUnsignedInt(str) passando uma String maior que 2^31-1 mas menor que 2^32-1 (ou seja, um número que cabe num unsigned int mas não cabe num int), o que o Java faz é:

  1. Transformar a String em binário

"4294967287" -> 11111111111111111111111111110111

  1. Representar este binário dentro de um int (ou seja, considerar que neste binário o bit mais significativo é o sinal)

1|1111111111111111111111111110111

  • Agora, se vc imprimir este int, como ele tem o bit de sinal ligado (ou seja, é um número negativo), o Java calculará o completemento de 2 dos 31 bits restantes pra poder saber qual é este número em decimal:
  1. Inverte os bits

1|0000000000000000000000000001000

  1. Soma 1

1|0000000000000000000000000001001

  1. Imprime -9
String str = "4294967287"; // 11111111111111111111111111110111
int result = Integer.parseUnsignedInt(str);
System.out.println(result); // -9

Reverse Integer solution

public int reverse(int x) {
    if (x == 0) return 0;

    String str = String.valueOf(x);
    String reversed = new StringBuilder(str).reverse().toString();

    if (x < 0) {
        reversed = "-" + reversed.substring(0, reversed.length() - 1);
    }

    try {
        return Integer.parseInt(reversed);
    } catch (Exception e) {
        return 0;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment