Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a integer into its separate digits

Say I have an integer, 9802, is there a way I can split that value in the four individual digits : 9, 8, 0 & 2 ?

like image 445
daihovey Avatar asked Aug 17 '11 23:08

daihovey


People also ask

How do you separate integers into digits?

You can convert a number into String and then you can use toCharArray() or split() method to separate the number into digits. String number = String.

How do you split an integer into digits in Python?

To split an integer into digits:Use the str() class to convert the integer to a string. Use a list comprehension to iterate over the string. On each iteration, use the int() class to convert each substring to an integer.

How do you extract digits from a number?

Extracting digits of a number is very simple. When you divide a number by 10, the remainder is the digit in the unit's place. You got your digit, now if you perform integer division on the number by 10, it will truncate the number by removing the digit you just extracted.


2 Answers

Keep doing modulo-10 and divide-by-10:

int n; // from somewhere
while (n) { digit = n % 10; n /= 10; }

This spits out the digits from least-significant to most-significant. You can clearly generalise this to any number base.

like image 55
Kerrek SB Avatar answered Sep 20 '22 14:09

Kerrek SB


You probably want to use mod and divide to get these digits.

Something like:

Grab first digit:

   Parse digit: 9802 mod 10 = 2
   Remove digit: (int)(9802 / 10) = 980

Grab second digit:

   Parse digit: 980 mod 10 = 0
   Remove digit: (int)(980 / 10) = 98

Something like that.

like image 30
Nadir Muzaffar Avatar answered Sep 20 '22 14:09

Nadir Muzaffar