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.
http://stackoverflow.com/questions/8033550/convert-integer-to-array-of-digits
– Luis Henrique
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).
– mgibsonbr
"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.
– Victor Stafusa
Exactly, I’m in doubt about this too.
– Dan Lucio Prada
@Danlucioprate See if my answer suits you, otherwise explain better what you want to do with the negative numbers.
– Victor Stafusa
@Danlucioprate Being that number
123
is equivalent to100*1 + 10*2 + 1*3
, the-123
is equivalent to100*(-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?– mgibsonbr
http://answall.com/help/on-topic
– Maniero