Print even digit first, odd digit later from a number
Problem statement: We have a number "13246598" where even, odd digits are jumbled. We need to print all even digits first followed by all even digits.
Output: 23145912
There may be multiple ways of doing it but I am doing it with java8 features. The way, I am trying to solve it will include some basic conversions which can help in any other such type of problems as well.
Steps:1. Convert this number to an Int array.
2. Create an integer list from that integer array.
3. Use the filter feature on that ArrayList each item to segregate even digits. Store them in an integer list.
4. Use the filter feature on that ArrayList each item to segregate odd digits. Store them in a new integer list.
5. Add all second list items to the first list
6. Convert this integer ArrayList to String and later that string to int Number.
7. print them
Input: Integer number =23145912;
//int number to intArray
1. int[] numberAsTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();
//int array to Integer list
2. List<Integer> al = Arrays.stream(numberAsTab).boxed().collect(Collectors.toList());
// Filter in integer list
3. List<Integer> al1 = al.stream().filter(i-> i%2 ==0).collect(Collectors.toList());
4. List<Integer> al2 = al.stream().filter(i-> i%2 !=0).collect(Collectors.toList());
5. al1.addAll(al2);
6. int number1 = Integer.parseInt(al1.stream().map(String::valueOf).collect(Collectors.joining()));
7. System.out.println(number1 );
Output: 24231591
So if we understood this solution, we can easily solve one more problem of printing all 0's and all 1's together from a given value.
Input: 10101110
Output: 00011111
We just need to change our filter condition with;
i-> i ==0
i-> i ==1
For this solution, don't convert the list of integers to int as we did above. Just try to print the list.
Why? For that, just do it and see the difference. :)