I am trying to create a function that will take an int and separately return the leftmost digit and the rest of the number.
int idigitizer(int *number) {
int i = 1;
int head = 0;
int tmp = 0;
tmp = *number;
while (tmp > 9) {
if ((tmp/i) < 10) {
head = tmp/i;
*number = *number - (head*i);
return head;
} else {
i = i*10;
}
}
number = 0;
return tmp;
}
idigitizer returns the leftmost part of the number and *number will carry the rest. I will have a loop in my main that will keep calling idigitizer until all the digits of the number get separated. The thing is I don't know how to handle zeroes and how to make this process terminate correctly when it is done with the last digit. Any help is welcome. Thanks in advance.
EDIT : To make it clearer. I don't want the possible zeroes in the middle of a number to get lost. If i get the number 100047 as input I want idigitizer to return:
return - *number
100047
1 00047
0 0047
0 047
0 47
4 7
7
I would use something like this instead:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int getFirstDigit( int number );
int getRestOfNumber( int number );
int getNumberOfMissingZeros (int number, int restOfNumber);
int main(int argc, char* argv[]){
int x = 500574;
int firstDigit;
int restOfNumber;
int n; /* loop index */
firstDigit = getFirstDigit(x);
restOfNumber = getRestOfNumber(x);
printf("The first digit of %d is %d.\n",x,firstDigit);
printf("The rest of the number is ");
for( n = 0; n<getNumberOfMissingZeros(x,restOfNumber); ++n ){
printf("0");
}
printf("%d.",restOfNumber);
return EXIT_SUCCESS;
}
int getFirstDigit( int number ){
return number / (int)floor( pow(10,floor(log10( (double)number ))) );
}
int getRestOfNumber( int number){
return number % (int)floor( pow(10,floor(log10( (double)number ))) );
}
int getNumberOfMissingZeros (int number, int restOfNumber){
int digitsOriginally;
int digitsInRestOfNumber;
digitsOriginally = floor(log10( (double)number ) );
digitsInRestOfNumber = floor(log10( (double)restOfNumber ) );
return digitsOriginally - digitsInRestOfNumber - 1;
}
The magic is in the expression (int)floor( pow(10,floor(log10( (double)number ))) );
This gets the size of the value, like for 52330, it would return 10000, since there are five digits in 52330. This makes it easy to extract the highest digit.