#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
/**
* Returns the digit at the specified position from the left.
*
* Example:
* number = 12345
* position = 1 -> 1
* position = 2 -> 2
* position = 3 -> 3
*/
int get_digit_from_left(unsigned long long number, unsigned int position)
{
unsigned long long divisor = 1;
unsigned int digits = 1;
/* Count digits */
unsigned long long temp = number;
while (temp >= 10) {
temp /= 10;
digits++;
divisor *= 10;
}
if (position == 0 || position > digits) {
return -1;
}
for (unsigned int i = 1; i < position; i++) {
number %= divisor;
divisor /= 10;
}
return (int)(number / divisor);
}
int main(void)
{
long long number = 12345;
printf("Digit 1: %d\n", get_digit_from_left(number, 1));
printf("Digit 2: %d\n", get_digit_from_left(number, 2));
printf("Digit 3: %d\n", get_digit_from_left(number, 3));
printf("Digit 5: %d\n", get_digit_from_left(number, 5));
return 0;
}
/*
run:
Digit 1: 1
Digit 2: 2
Digit 3: 3
Digit 5: 5
*/