How to get the Nth digit of a number in C

2 Answers

0 votes
#include <stdio.h>

int main(void) {
    int number = 76594;
	char s[10] = "";
	int N = 4;
	
    sprintf(s, "%d", number); 
    printf("%c\n", s[N - 1]);
	
	int x = s[N - 1] - '0';
	printf("%d\n", x);
     
    return 0;
}
 
 
 
/*
run:
 
9
9
 
*/

 



answered Jun 1, 2020 by avibootz
edited 1 day ago by avibootz
0 votes
#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

*/

 



answered 1 day ago by avibootz
...