Break an integer into small parts in Java

Asked

Viewed 784 times

0

I need to place each digit of an integer in a vector position.

int a = 123;
List<Integer> numerosGerados = new ArrayList<>();

And now I need to put the number 1 at the 0 position of the array, number 2 in 1 and so on. The number may be negative.

  • 1

    http://stackoverflow.com/questions/8033550/convert-integer-to-array-of-digits

  • 1

    You need an arithmetic method, such as in that other question of yours, or is one involving strings enough? A little more context would help, for example if this is some exercise or if it is to be used in practice (and if it is in practice, so that).

  • 2

    "And in case the number is negative" ... What happens? Ignores the minus sign, gives an error or you have to put the minus sign on the list? If it is the last option then complicated, because the minus sign alone is not an integer.

  • Exactly, I’m in doubt about this too.

  • @Danlucioprate See if my answer suits you, otherwise explain better what you want to do with the negative numbers.

  • 2

    @Danlucioprate Being that number 123 is equivalent to 100*1 + 10*2 + 1*3, the -123 is equivalent to 100*(-1) + 10*(-2) + 1*(-3), so one option is to make all "digits" negative. Another option is simply to "mark" the number as negative, changing the first digit only (as done by Victor and me in our responses). Again, I ask, what is the purpose of this?

  • http://answall.com/help/on-topic

Show 2 more comments

4 answers

9


Response based on the mgibsonbr, but without having to invert the list:

int a = 123;
List<Integer> numerosGerados = new ArrayList<>();

int x = a > 0 ? a : -a;
do {
    numerosGerados.add(0, x % 10);
    x /= 10;
} while (x > 0);

if (a < 0) numerosGerados.set(0, -numerosGerados.get(0));

If the number given is negative, the first item in the list will also be negative.

  • 2

    By the way, your answer is better than mine, I have this habit of "insert at the beginning of the list is inefficient" - when in reality the size of the entries is so small that it shouldn’t make much difference... (unless this code is used a very large number of times, of course)

  • 2

    @mgibsonbr at least we have 4 different solutions :) and agree that is the best so far.

6

Mathematically solving:

import java.util.*;

class Ideone {
    public static void main (String[] args) {
        ImprimeLista(SeparaDigitos(12345));
        ImprimeLista(SeparaDigitos(-123));
        ImprimeLista(SeparaDigitosNegativo(-123));
        ImprimeLista(SeparaDigitosNegativo(123));
    }
    public static List<Integer> SeparaDigitos(int valor) {
        List<Integer> numerosGerados = new ArrayList<>();
        int positivo = Math.abs(valor);
        int tamanho = (int)(Math.log10(positivo) + 1);
        int posicao = 0;
        while(posicao < tamanho) {
            int digito = valor / (int)Math.pow(10, tamanho - posicao - 1) * Integer.signum(valor);
            numerosGerados.add(digito);
            valor %= digito * Math.pow(10, tamanho - posicao - 1);
            posicao++;
        }
        return numerosGerados;
    }
    public static List<Integer> SeparaDigitosNegativo(int valor) {
        List<Integer> numerosGerados = new ArrayList<>();
        int positivo = Math.abs(valor);
        int tamanho = (int)(Math.log10(positivo) + 1);
        int posicao = 0;
        while(posicao < tamanho) {
            int digito = valor / (int)Math.pow(10, tamanho - posicao - 1) * (posicao == 0 ? 1 : Integer.signum(valor));
            numerosGerados.add(digito);
            valor %= digito * Math.pow(10, tamanho - posicao - 1);
            posicao++;
        }
        return numerosGerados;
    }
    public static void ImprimeLista(List<Integer> lista) {
        for (int item : lista) {
            System.out.println(item);
        }
        System.out.println();
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I put in two ways to treat negative, one that ignores the sign and one that considers the sign in the first digit.

  • In this case, it only works for positive numbers, I edited my question specifying that it needs to be both positive and negative.

  • 3

    These requirements are kind of weird and are never well defined, I treated how I think you can treat the negatives in the presented form, probably this doesn’t make much sense. You need to better inform what you are doing, what the purpose of this is, otherwise these questions will likely generate discussions on http://meta.pt.stackoverflow.com to decide what to do with them. If you need the negative to be treated differently you can do but you need to explain where these requirements come from.

4

This is a case where it is easier to get the digits in reverse order, and then flip the list. For to get the last digit of a positive integer just do the rest of the division by 10:

int a = -123;
List<Integer> numerosGerados = new ArrayList<>();

boolean negativo = (a < 0);
int x = negativo ? -a : a;
do {
    numerosGerados.add(x % 10);
    x /= 10;
} while (x > 0);
Collections.reverse(numerosGerados); // Inverte a lista

if ( negativo ) {
    // ??? (não dá pra colocar um "-" numa lista de inteiros...)

    // Exemplo: faz com que o primeiro deles seja negativo
    int primeiro = numerosGerados.get(0);
    numerosGerados.set(0, -primeiro);
}

Upshot: [-1,2,3]

2

int value = 12345;
ArrayList<Integer> array = new ArrayList<>();

for(char each : Integer.toString(value).toCharArray())
   array.add(Integer.parseInt(Character.toString(each)));

Example working on Ideone

Browser other questions tagged

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