-4

I've been trying to use this following simple code for a function call, but somehow it's been giving me an error message, saying % operator is binary operatir, and it's not for int.

int getDigit(int num, int index)
{int temp;
temp = num%pow(10,index);
return (temp)}

Preconditions : num - positive integer, index- finding index's digit (e.g. num = 6947, index = 3, return would be 9

Please advise, I really didn't expect to get stuck here for this long time.

Minjae
  • 31
  • 1
  • 2
  • 8

2 Answers2

1

I'm only writing this because the other answers are dangerously wrong.

Here is a simple, slow and fool-proof solution:

#include <iostream>
#include<cmath>
int getDigit(int num, int index)
{
    // first shift index -1 digits to the right to position the indexth digit
    while(--index)
    {
        num /= 10;
    }
    // now strip off everything after the indexth digit
    num %= 10;
    // could be negative, but we only want digit. Lose the sign
    return std::abs(num);
}

int main()
{
    std::cout <<getDigit(6947, 3) << std::endl;
}

Output

9

Here is a faster, less safe non-portable solution that only works with a 32 bit integer.

int divisors[] =
{
    1,
    10,
    100,
    1000,
    10000,
    100000,
    10000000,
    100000000,
    1000000000,
};
int getDigit32(int num, int index)
{
    if (index <=10)
    {
        return std::abs((num/divisors[index -1])%10);
    }
    return -1;
}

I think it can be generalized by generating the array with template meta programming, but I'll be honest and admit I'm not good at that stuff. I'm struggling to find a good terminating condition.

user4581301
  • 33,082
  • 7
  • 33
  • 54
0

VS tells right of % couldn't be double

This compiled normally:

int getDigit(int num, int index)
{
  int temp;
  temp=num%static_cast<int>(pow(10, index));
  return (temp);
}