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?
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.
Why implement the conversion yourself when there's already a very reliable way to do it?
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;
}
//add the last digit
digits.Add(number);
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();
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))
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)
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;
Not sure if I understood what you want correctly...
Would the below work for you?? It is written in C#...
public static List<int> ExtractDigit()
{
// Input example
int number = 12345;
// Convert Integer to string
string numberedString = number.ToString();
// Create a list of integers
var numList = new List<int>();
// Convert each character in string back to int and add to list.
foreach (char c in numberedString)
{
numList.Add(Convert.ToInt32(c.ToString()));
}
return numList;
}
I hope i was of help.
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.
Here are reversible array functions in JavaScript that handle integers or strings:
function reverse(array)
{
var left = null;
var right = null;
var length = array.length;
for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
{
var temporary = array[left];
array[left] = array[right];
array[right] = temporary;
}
return array;
}
function toDigitsArrayFromInteger(integer, isReverse)
{
var digits = [];
if (integer > 0)
{
var floor = window.Math.floor;
while (integer > 0)
{
digits.push(floor(integer % 10));
integer = floor(integer / 10);
}
// Array is populated in reverse order. Un-reverse it to make it normal.
if (!isReverse)
{
digits = reverse(digits);
}
}
else if (integer < 0)
{
digits = toDigitsArrayFromInteger(-integer, isReverse);
}
else if (integer === 0)
{
digits.push(0);
}
return digits;
}
function toDigitsArrayFromString(string, isReverse)
{
var digits = [];
string += ""; // Coerce to string.
var i = null;
var length = string.length;
for (i = 0; i < length; i += 1)
{
var integer = parseInt(string.charAt(i), 10);
if (isFinite(integer))
{
digits.push(integer);
}
}
if (isReverse)
{
digits = reverse(digits);
}
return digits;
}
Once you have the digits as an array, you can reverse the array easily to get the digits starting from the left or from the right.
The string function is more versatile because it can find any digit in a string, whereas the integer function is limited to integers.
Benchmarks: http://jsperf.com/todigitsarray
The benchmarks between the two functions show that in Firefox 10 and Chrome 12, the string function is 30% to 60% faster than the integer function. In Opera 12, the integer function is slightly faster by about 10%.
Following program would work as well.
public class Main {
public static void main(String[] args) {
int i1 =123456;
String s =new StringBuilder(String.valueOf(i1)).toString();
char a[]=s.toCharArray();
for(char c : a) {
Integer i = Integer.parseInt(c+"");
System.out.println(i);
}
}
}
JavaScript:
function digits(num) {
return String(num).split('').map(v => +v);
}
精彩评论