Home > Article > Backend Development > 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!