Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract each digit from a number?

Tags:

math

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?

like image 439
ronT Avatar asked Sep 01 '10 00:09

ronT


People also ask

How do you extract individual 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.

How do I extract individual numbers from a number in Python?

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.

How do you find digits in a number?

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.


1 Answers

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.

like image 128
nickf Avatar answered Sep 22 '22 05:09

nickf