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
if digit is meant to be a Character
String numstr = Integer.toString( 123 );
Pattern.compile( "" ).splitAsStream( numstr ).map(
s -> s.charAt( 0 ) ).toArray( Character[]::new ); // [1, 2, 3]
and the following works correctly
numstr = "000123"
gets [0, 0, 0, 1, 2, 3]
numstr = "-123"
gets [-, 1, 2, 3]
Something like this will return the char[]
:
public static char[] getTheDigits(int value){
String str = "";
int number = value;
int digit = 0;
while(number>0){
digit = number%10;
str = str + digit;
System.out.println("Digit:" + digit);
number = number/10;
}
return str.toCharArray();
}
simple solution
public static void main(String[] args) {
int v = 12345;
while (v > 0){
System.out.println(v % 10);
v /= 10;
}
}
Java 9 introduced a new Stream.iterate
method which can be used to generate a stream and stop at a certain condition. This can be used to get all the digits in the number, using the modulo approach.
int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
Note that this will get the digits in reverse order, but that can be solved either by looping through the array backwards (sadly reversing an array is not that simple), or by creating another stream:
int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
or
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length - i]).toArray();
As an example, this code:
int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
Will print:
[0, 0, 4, 3, 2, 1]
[1, 2, 3, 4, 0, 0]
Just to build on the subject, here's how to confirm that the number is a palindromic integer in Java:
public static boolean isPalindrome(int input) {
List<Integer> intArr = new ArrayList();
int procInt = input;
int i = 0;
while(procInt > 0) {
intArr.add(procInt%10);
procInt = procInt/10;
i++;
}
int y = 0;
int tmp = 0;
int count = 0;
for(int j:intArr) {
if(j == 0 && count == 0) {
break;
}
tmp = j + (tmp*10);
count++;
}
if(input != tmp)
return false;
return true;
}
I'm sure I can simplify this algo further. Yet, this is where I am. And it has worked under all of my test cases.
I hope this helps someone.
// could be any num this is a randomly generated one
int num = (int) (Math.random() * 1000);
// this will return each number to a int variable
int num1 = num % 10;
int num2 = num / 10 % 10;
int num3 = num /100 % 10;
// you could continue this pattern for 4,5,6 digit numbers
// dont need to print you could then use the new int values man other ways
System.out.print(num1);
System.out.print("\n" + num2);
System.out.print("\n" + num3);