views:

289

answers:

6

I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.

How can I get it in Java?

+12  A: 

Convert it to String and use String#toCharArray() or String#split().

String number = String.valueOf(someInt);

char[] digits1 = number.toCharArray();
// or:
String[] digits2 = number.split("(?<=.)");
BalusC
This is the quick and dirty way.
jjnguy
With `split("")`, the first item in the array is `""`. Use other regex, like `split("(?<=.)")`.
True Soft
@jjn: That's right :) @True Soft: thanks for regex improvement, I edited it in.
BalusC
+15  A: 

To do this, you will use the % (mod) operator.

int number; // = and int

while (number > 0) {
    print( number % 10);
    number = number / 10;
}

The mod operator will give you the remainder of doing int division on a number.

So,

10012 % 10 = 2

Because:

10012 / 10 = 1001, remainder 2

Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.

Code to print the numbers in the correct order:

int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
    stack.push( number % 10 );
    number = number / 10;
}

while (!stack.isEmpty()) {
    print(stack.pop());
}
jjnguy
Thanks for your reply. What is the value of the num? What does it stands for?
Edy Moore
This will get you the numbers in the wrong order, however, so you'll have to be sure and push them onto a stack or just put them in an array in reverse order.
Paul Tomblin
Note that this gives them right-to-left. (The OP's example shows them left-to-right). Simple enought to handle, but it should be noted.
James Curran
@Kap, it was a typo. It should have been `number`. You should also look at the note posted at the bottom of the answer.
jjnguy
@Paul, @James Thanks for pointing that out.
jjnguy
Would you prefer this over using a String-based approach? Your approach is nice in the sense that it's all mathematics-based, but gives the same result and is more lines of code.
Don Branson
@Don, in practice, no. I would not favor this. It is **way** faster than the string based version though. I would look at [Marimuthu's](http://stackoverflow.com/questions/3389264/how-to-get-the-separate-digits-of-an-int-number/3390244#3390244) answer though for some fast and short code.
jjnguy
Yes, definitely faster, almost 3x based on a quick test. I like either approach, depending on what the goal is. Also, I modified my answer to give numeric digits in addition to character digits.
Don Branson
+2  A: 

I'm not familiar with Java's internals, but couldn't you simply modulus the number by 10 repeatedly, and store the result in a variable?

kevinmajor1
Yes, you can do that.
jjnguy
I guess you can. :-P
kevinmajor1
Thanks everybody
Edy Moore
+1  A: 

Integer.toString(1100) gives you the integer as a string. Integer.toString(1100).getBytes() to get an array of bytes of the individual digits.

Edit:

You can convert the character digits into numeric digits, thus:

  String string = Integer.toString(1234);
  int[] digits = new int[string.length()];

  for(int i = 0; i<string.length(); ++i){
    digits[i] = Integer.parseInt(string.substring(i, i+1));
  }
  System.out.println("digits:" + Arrays.toString(digits));
Don Branson
This is slightly misleading. This will give you an array of bytes representing the char `'1'` or `'0'`. The byte values wont be `1`, or `0`.
jjnguy
Misleading? That's a little harsh. The question was ambiguous. It really depends what he wants to do with the digits. You're assuming that he wants to perform calculations. My answer assumes text processing. Either assumption is partially correct, but it was not my intent to mislead.
Don Branson
@Don, I guess I feel it is misleading because you get an array of bytes, which I think of *numbers* not characters.
jjnguy
@Justin - Ah, okay. I don't automatically associate bytes as not characters. In my assembly days, I'd increment 'a' to get 'b', iterating through the alphabet - so sometimes bytes were simultaneously both. Of course, high-level languages and UTF render that all moot.
Don Branson
A: 

Basically I agree with BalusC. But note that this gives characters, which may or may not be what you want. That is, you'll get the character '1' rather than 1. But this is easily converted by subtracting '0'. For example:

char[] charDigits=Integer.toString(n).toCharArray();
int[] digits=new int[charDigits.length];
for (int p=0;p<charDigits.length;++p)
  digits[p]=charDigits[p]-'0';
return digits;

Okay, this won't work if you have some Unicode digits that don't fall in the range of '0' to '9', but I'm not sure if there are any such, and in any case I don't think you're going to get them out of Integer.toString.

Jay
ALternatively, you can use Character.digit(charDigits[p],10) to convert a char digit to an int.
dogbane
Oooh, I wasn't aware of the Character.digit function. That's surely safer. That will work with Arabic digits, Oriya, Tamil, Telugu, and a bunch of other Unicode characters that don't display on my browser. If you set your locale to Saudi Arabia do you get Arabic digits when you do an Integer.toString()? Or do they still come out in "English Arabic" digits? Someday when I have free time maybe I'll play with that.
Jay
+4  A: 

How about this?

public static void printDigits(int num) {
    if(num / 10 > 0) {
        printDigits(num / 10);
    }
    System.out.printf("%d ", num % 10);
}

or instead of printing to the console, we can collect it in an array of integers and then print the array:

public static void main(String[] args) {
    Integer[] digits = getDigits(12345);
    System.out.println(Arrays.toString(digits));
}

public static Integer[] getDigits(int num) {
    List<Integer> digits = new ArrayList<Integer>();
    collectDigits(num, digits);
    return digits.toArray(new Integer[]{});
}

private static void collectDigits(int num, List<Integer> digits) {
    if(num / 10 > 0) {
        collectDigits(num / 10, digits);
    }
    digits.add(num % 10);
}
Marimuthu Madasamy
That's a good way to print things in the correct order using mod. `+1`
jjnguy
This is beautiful. I was thinking: "There has to be a way to reverse the order without using a Collection...." `+1`
bobndrew