Home > Java > javaTutorial > How Can I Extract Individual Digits from an Integer in Java?

How Can I Extract Individual Digits from an Integer in Java?

Patricia Arquette
Release: 2024-12-19 20:34:11
Original
567 people have browsed it

How Can I Extract Individual Digits from an Integer in Java?

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;
}
Copy after login

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());
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template