¿Cómo saber qué número es el segundo dígito en?:
int numero = 15
S2.
El resto de la división por 10 te dará dicho número.
Saludos.
Completando la explicación de Berserker:
CitarYo man all u need to do is apply successive division and modulo.e.g lets say u hv 1234 as ur 4digit number.if you take the modulo of it by 10, you will get the last integer which is 4 in this case( 1234%10 ).And also when you divide the number by 10 you will get 123.4( 1234/10 ), so u save the result in an integer so it will be 123 since u have already taken the last digit and stored in a variable. take ur new number and modulo 10 again u will get 3......and so on...
Y si aun así no lo entiendes, siempre te quedará la guarrada de convertir el int a string y luego leer cada caracter.. pero realmente es innecesario.
Cita de: "ZaelSiuS"
Y si aun así no lo entiendes, siempre te quedará la guarrada de convertir el int a string y luego leer cada caracter.. pero realmente es innecesario.
Strings, mmm... muy interesante.
S2.
Ambas funcionan y devuelven -1 en caso de error :D
int digitos(int pos, int num)
{
if (pos<=0) return -1;
if (pos = 1) return num%10;
else return digitos(pos-1,num/10);
}
int digitos(int pos, int num)
{
int res = -1;
while (pos>0)
{
res = num%10;
num = num/10;
pos--;
}
return res;
}
Esta es mi version single line del hermoso codigo de shephiroth:
template <int B = 10> int digit(int n, int p) { assert(p>=0); return (p>1?digit<B>(n/B,p-1):n%B); }