How do I get what the digits of a number are in C++ without converting it to strings or character arrays?
The following prints the digits in order of ascending significance (i.e. units, then tens, etc.):
do {
int digit = n % 10;
putchar('0' + digit);
n /= 10;
} while (n > 0);
Get all the individual digits into something like an array - two variants:
int i2array_BigEndian(int n, char a[11])
{//storing the most significant digit first
int digits=//obtain the number of digits with 3 or 4 comparisons
n<100000?n<100?n<10?1:2:n<1000?3:n<10000?4:5:n<10000000?n<1000000?6:7:n<100000000?8:n<1000000000?9:10;
a+=digits;//init end pointer
do{*--a=n%10;}while(n/=10);//extract digits
return digits;//return number of digits
}
int i2array_LittleEndian(int n, char a[11])
{//storing the least significant digit first
char *p=&a[0];//init running pointer
do{*p++=n%10;}while(n/=10);//extract digits
return p-a;//return number of digits
}
Integer version is trivial:
int fiGetDigit(const int n, const int k)
{//Get K-th Digit from a Number (zero-based index)
switch(k)
{
case 0:return n%10;
case 1:return n/10%10;
case 2:return n/100%10;
case 3:return n/1000%10;
case 4:return n/10000%10;
case 5:return n/100000%10;
case 6:return n/1000000%10;
case 7:return n/10000000%10;
case 8:return n/100000000%10;
case 9:return n/1000000000%10;
}
return 0;
}