hi, i have difficulty on this question, can someone please tell me how to do it. ?
example = nthDigit(12345, 3) will return the number 4..
the question is :
Code:int nthDigit(int number, int n)
{
}
Printable View
hi, i have difficulty on this question, can someone please tell me how to do it. ?
example = nthDigit(12345, 3) will return the number 4..
the question is :
Code:int nthDigit(int number, int n)
{
}
NOTE this is not school work , just for my own purpose on understanding. thank you
You can parse digits with modulus and division. Think about it for a bit. Maybe experiment and see what happens. Then from there you can write the function.
or the rough and slow approach of turning it into a string, taking the nth character from that string, and returning that as an int.
Slow, ugly as hell, but it works.
And used more often than you think, especially when the original data is stored as strings which is so often the case (anything coming out of networks through http for example).
Heck, you can use stringstreams to do that as well:
1) Read the number into an ostringstream, which will turn it into a string.
2) Then you can get the string from the ostringstream using the str() member function.
3) Then you can pick out the nth digit using array notation, e.g. myStr[3], and you can use one of the string constructors to create a string out of the char you have, e.g. string(1, myStr[3]).
4) You can use the 1 digit string from 3) to create an istringstream object. Finally, you can read from the istringstream into an int type. Voila! You will have the digit as a numeric type--and without doing any math.