All I can think of is to repeatedly divide the number by 10 (until number is less than 10) and keep a count, but is there a trick for this sort of thing?
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.
Making use of isdigit() function to extract digits from a Python string. Python provides us with string. isdigit() to check for the presence of digits in a string. Python isdigit() function returns True if the input string contains digit characters in it.
The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.
Yep, you pretty much have the mathematical way to do it right there.
while (num >= 10)
digit = num MOD 10 // and save this into an array or whatever
num = num / 10
at the end of this, num
will contain the last digit.
Here's a Javascript implementation:
function getDigits(num) {
var digits = [];
while (num >= 10) {
digits.unshift(num % 10);
num = Math.floor(num / 10);
}
digits.unshift(num);
return digits;
}
Note that it only works for non-negative integers.
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