No such function exists as far as I can see. Rolling your own has some gotchas which are worth discussing.
I ran three options (splitting a string and doing a modulus operation and making a char array) through some parameters, and this is the most "efficient" I could see. Note some assumptions:
- We have to support Long
- We retain the fact the sign bit of the number, but not in the array.
First the modulus route, which on first glance should be the most efficient. However, if the number is truly long (as in exceeds the maximum value of an int) then the mod operator overflows and gives junk results. So then we have to move to BigInteger (as far as I can tell, if someone sees a better solution, please comment):
public static void main(String[] args) {
long x = 981212131233123L;
int[] r = new int[calculateSize(x)];
boolean positive = fillArrayWithDigits(x, r);
//r = [9, 8, 1, 2, 1 ...
}
private static boolean fillArrayWithDigits(long y, int[] r) {
boolean positive = y >= 0;
y = Math.abs(y);
BigInteger ten = BigInteger.valueOf(10);
for (int i = r.length; i > 0; i--) {
r[i-1] = BigInteger.valueOf(y).mod(ten).intValue();
y /= 10L;
}
return positive;
}
private static int calculateSize(long y) {
int size = 0;
do {
size++;
y /= 10L;
} while (y != 0);
return size;
}
At the end of this, you have a boolean indicating if the number was positive, and an array containing the numbers.
In terms of doing a string parse, the "best" I could come up with was:
public static void main(String[] args) {
long x = 981212131233123L;
boolean positive = x >= 0;
x = Math.abs(x);
String[] s = Long.toString(x).split("");
int[] r = new int[s.length - 1];
for (int i = r.length; i > 0; i--) {
r[i-1] = Integer.parseInt(s[i]);
}
//r = [9, 8, 1, 2, 1 ...
}
The char array method was very similar:
public static void main(String[] args) {
long x = 981212131233123L;
boolean positive = x >= 0;
x = Math.abs(x);
char[] s = Long.toString(x).toCharArray();
int[] r = new int[s.length];
for (int i = r.length - 1; i > -1; i--) {
r[i] = Character.digit(s[i], 10);
}
//r = [9, 8 ,1, 2, 1 ....
}
But seems the most efficient