Home >Java >javaTutorial >How Can I Efficiently Extract Individual Digits from an Integer in Java?
In Java, there are multiple approaches to obtain the individual digits of an integer, one of which involves utilizing the modulo operator.
By repeatedly applying the modulo operator on a number, you can isolate each digit in a loop:
int number; // = some int while (number > 0) { System.out.print( number % 10); // Extract the last digit number /= 10; // Truncate the number }
This approach returns the individual digits in reverse order. To obtain the correct order, you can push the digits onto a stack and pop them off in reverse order.
int number; // = and int LinkedList<Integer> stack = new LinkedList<Integer>(); // Stack for digits while (number > 0) { stack.push( number % 10 ); // Push the last digit number /= 10; // Truncate the number } while (!stack.isEmpty()) { System.out.print(stack.pop()); // Pop the digits in correct order }
This method provides an efficient way to extract and process the individual digits of an integer in Java.
The above is the detailed content of How Can I Efficiently Extract Individual Digits from an Integer in Java?. For more information, please follow other related articles on the PHP Chinese website!