4

Possible Duplicate:
How to get the digits of a number without converting it to a string/ char array?

I am stuck doing this task in C++; what I want to do is to figure out the the units digit and the tens digits of any number given by the user.

For example, if the number is 9775, the units digit is obtained as 9775 % 10, but I am stuck finding the tens digit.

Community
  • 1
  • 1
Junaid
  • 1,270
  • 3
  • 14
  • 33

3 Answers3

15

For a non-negative integer x the tens digit is (x / 10) % 10.

arx
  • 16,686
  • 2
  • 44
  • 61
4
#include <math.h>

int getdigit(int number, int digit)
{
   return (number / ((int) pow(10, digit)) % 10);
}

Where the first digit is 0. I don't really like floating point numbers getting involved (via pow), though.

Rivasa
  • 6,510
  • 3
  • 35
  • 64
LubosD
  • 781
  • 6
  • 18
3

Try to use very rarely used functions:

http://www.cplusplus.com/reference/clibrary/cstdlib/div/

 div_t div (           int numer,           int denom );
 ldiv_t div (      long int numer,      long int denom );  // C++ only
lldiv_t div ( long long int numer, long long int denom );  // C++11 only

E.g. with a simple loop:

std::vector<int> getDigits(unsigned int numer)
{
  std::deque<int> rv;
  do {
     div_t res = div(numer, 10);
     rv.push_front(res.rem);
     numer = res.quot;
  } while (numer > 0);
  return std::vector<int>(rv.begin(), rv.end());  
}
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112