Home  >  Article  >  Backend Development  >  How do you convert an integer into a list of its individual digits?

How do you convert an integer into a list of its individual digits?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 00:27:02799browse

How do you convert an integer into a list of its individual digits?

Splitting an Integer into a List of Digits

Given an integer, like 12345, you may require a way to decompose it into a list of individual digits [1, 2, 3, 4, 5]. To achieve this, follow the steps below:

Solution:

To address this, we can leverage the inherent string representation of an integer. By converting the integer to a string, we gain the ability to iterate through its individual characters. Subsequently, for each character, which represents a digit, we can reconvert it back to an integer using a list comprehension.

Example:

Consider the example provided in the original question, where the input integer is 12345. To obtain our desired result, we would execute the following code:

num_as_string = str(12345)
digit_list = [int(digit) for digit in num_as_string]

# Print the resulting list of digits
print(digit_list)  # Output: [1, 2, 3, 4, 5]

The above is the detailed content of How do you convert an integer into a list of its individual digits?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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