Extracting Individual Digits from an Integer in Java
Given a series of integers such as 1100, 1002, or 1022, you may encounter the need to extract the individual digits, obtaining values like [1, 1, 0, 0].
To accomplish this in Java, the % (mod) operator proves invaluable. This operator provides the remainder after performing integer division on a number.
Utilizing this operator effectively, you can develop a straightforward code solution:
int number = 1100; while (number > 0) { System.out.print(number % 10); number = number / 10; }
In the given example, the mod operator determines the last digit of number by calculating 1100 % 10, which results in 0. The number is then updated to 1100 / 10, resulting in 110.
However, this method presents the digits in reverse order (0, 1, 1). To obtain the digits in the correct order, a stack-based approach is employed:
int number = 1100; LinkedList<Integer> stack = new LinkedList<>(); while (number > 0) { stack.push(number % 10); number = number / 10; } while (!stack.isEmpty()) { System.out.print(stack.pop()); }
This revised code utilizes a stack data structure to push the extracted digits onto a stack in reverse order. The pop() operation is then used to retrieve the digits in the correct order, effectively displaying [1, 1, 0, 0] in the example provided.
The above is the detailed content of How Can I Extract Individual Digits from an Integer in Java?. For more information, please follow other related articles on the PHP Chinese website!