Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a Specific Digit of a Number

Tags:

c++

integer

digit

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?

like image 464
Maxpm Avatar asked Dec 10 '10 15:12

Maxpm


People also ask

How do you find the one digit of a number?

To find first digit of a number we divide the given number by 10 until number is greater than 10. At the end we are left with the first digit.

How do you find the nth digit of a number?

Approach: The idea is to skip (N-1) digits of the given number in base B by dividing the number with B, (N – 1) times and then return the modulo of the current number by the B to get the Nth digit from the right.

How do I find a specific digit in Python?

Python String isdigit() Method The isdigit() method returns True if all the characters are digits, otherwise False. Exponents, like ², are also considered to be a digit.


2 Answers

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

just define the function intPower.

like image 135
Cheers and hth. - Alf Avatar answered Oct 10 '22 12:10

Cheers and hth. - Alf


You can also use the % operator and / for integer division in a loop. (Given integer n >= 0, n % 10 gives the units digit, and n / 10 chops off the units digit.)

like image 31
Mitch Schwartz Avatar answered Oct 10 '22 12:10

Mitch Schwartz