This isn't a homework question. 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 fo thing?
If it is an Integer, you could convert the string representation into an array of characters, and then convert that into an array of bytes (0-9)
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.
Python code using your approach:
def digits(n):
ds = []
while n > 0:
ds.append(n % 10)
n /= 10
ds.reverse()
return ds
Using convertation to string:
def digits(n):
return map(int, str(n))
Why implement the conversion yourself when there's already a very reliable way to do it? (And since it's not homework).
In pseudo-C:
char digits[10];
sprintf(digits, "%d", number);
Now your digits char array (string) should consist of each digit of the number. Most other scripting languages also contain a sprintf function.
This will work if you want base 8 or base 16 or binary, etc. Just use a different format specifier.
The mathematical answer is to mod by 10 and add each result to a list, then reverse the list's order. Here's a basic C# algorithm that will do this:
List<byte> digits = new List<byte>();
while(number > 10)
{
digits.Add(number % 10);
number %= 10;
}
byte temp;
for(var i=0;i<digits.Count/2;i++)
{
temp = digits[i];
digits[i] = digits[digits.Count-(i+1)];
digits[digits.Count-(i+1)] = temp;
}
Other "tricks" usually involve a string conversion. Here's a C# one-liner using Linq that will give the same result as the above:
var digits = number.ToString().Select(c=>byte.Parse(c)).ToList();
A more efficient algorithm, if your input numbers may be large, is to divide by a power of 10, say 1000, and use a lookup table:
s = ""; // or use a string builder appropriate to your language...
table = {"000", "001", ..., "999"};
tableInitial = {"unused", "1", "2", ..., "9", "10", ..., "999"};
while(n >= 1000) {
m = n%1000;
n /= 1000;
s = table[m] + s;
}
s = tableInitial[n] + s;
The given python solution could be further optimized using
zerostr = ord('0')
def digits(n):
return map(lambda x: ord(x)-zerostr, str(n))
In fact, where the int -> str
conversion is probably completely optimized, to get the numeric value it's much better to use the instrinsic character value of the digit string, which in every encoding (including EBCDIC) gives the numeric value by means of an int
subtraction instead of a str
parsing.