Finding a Specific Digit of a Number

2019-01-24 09:52发布

I'm trying to find the nth digit of an integer of an arbitrary length. I was going to convert the integer to a string and use the character at index n...

char Digit = itoa(Number).at(n);

...But then I realized the itoa function isn't standard. Is there any other way to do this?

9条回答
Explosion°爆炸
2楼-- · 2019-01-24 10:19
number = 123456789
n = 5

tmp1 = (int)(number / 10^n);   // tmp1 = 12345
tmp2 = ((int)(tmp1/10))*10;    // tmp2 = 12340
digit = tmp1 - tmp2;           // digit = 5
查看更多
forever°为你锁心
3楼-- · 2019-01-24 10:20

A direct answer is:

char Digit = 48 + ((int)(Number/pow(10,N)) % 10 );

You should include the <math> library

查看更多
男人必须洒脱
4楼-- · 2019-01-24 10:21

(number/intPower(10, n))%10

just define the function intPower.

查看更多
登录 后发表回答