Say I have an integer, 9802, is there a way I can split that value in the four individual digits : 9, 8, 0 & 2 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With