P
P
prohoroffff2016-02-01 19:38:53
C++ / C#
prohoroffff, 2016-02-01 19:38:53

How to find the nth digit of a decimal number?

How to find the nth digit of a decimal number?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
alexxandr, 2016-02-02
@prohoroffff

f(N, m) = (N div 10^(m-1)) mod 10
div - integer division
mod - taking remainder
N - number
m - digit number
ae:
N = 1324
m = 3
1324 / 100 = 13
13% 10 = 3

B
bromzh, 2016-02-01
@bromzh

#include <stdio.h>

int digit(int number, int n) {
  if (n <= 1) {
    return number % 10;
  }
  return digit(number / 10, n - 1);
}

int main(void) {
  printf("%i\n", digit(12345, 1));
  printf("%i\n", digit(12345, 2));
  printf("%i\n", digit(12345, 3));
  printf("%i\n", digit(12345, 4));
  return 0;
}

https://ideone.com/ZSHndh

A
Alexander Ananiev, 2016-02-01
@SaNNy32

You can, as an option, translate the number into a string and take the nth index

H
Hakito, 2016-02-01
@hakito

you take the remainder of dividing by 10 - you get the last digit, then you divide the number by 10, removing the last digit. And so on until you reach the desired

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question