I want to be able to extract separate digits from a numbe. Lets say the year is 1981 then i want to be able to put the digit 9 in a variable, then I also want to be able to put the whole number in an variable.
How can I do this?
Extracting singel digits from an int.
Started by Christine, Jan 17 2008 11:48 AM
2 replies to this topic
#1
Posted 17 January 2008 - 11:48 AM
|
|
|
#2
Posted 17 January 2008 - 01:51 PM
Use the modulus base ten of the number after removing the preceding digits.
[HIGHLIGHT="C++"]
int extractDigit(int number, int place)
{
for(int i = 0; i < place; ++i)
number /= 10; //get rid of the preceding digits
return number % 10; //now ignore all of the following ones
}
[/HIGHLIGHT]
To make it more generic, so that you can extract hex digits, just replace the tens with a variable called radix that'll be passed in as an argument.
[HIGHLIGHT="C++"]
int extractDigit(int number, int place)
{
for(int i = 0; i < place; ++i)
number /= 10; //get rid of the preceding digits
return number % 10; //now ignore all of the following ones
}
[/HIGHLIGHT]
To make it more generic, so that you can extract hex digits, just replace the tens with a variable called radix that'll be passed in as an argument.
#3
Posted 18 January 2008 - 09:23 AM
Adding to dargueta's response: the key to extracting digits is using integer and modular division. You could directly access the 9 in 1981 with (1981 / 100) % 10. The reason this works is that 1981/100 = 19, and 19 % 10 = 9.


Sign In
Create Account

Back to top









