Foros - Stratos

Programadores => General Programadores => Mensaje iniciado por: J_F_NASH en 09 de Abril de 2007, 05:19:31 PM

Título: ¿Cómo comparar digitos en un entero?
Publicado por: J_F_NASH en 09 de Abril de 2007, 05:19:31 PM
¿Cómo saber qué número es el segundo dígito en?:
int numero = 15



S2.
Título: ¿Cómo comparar digitos en un entero?
Publicado por: BeRSeRKeR en 09 de Abril de 2007, 05:44:36 PM
El resto de la división por 10 te dará dicho número.

Saludos.
Título: ¿Cómo comparar digitos en un entero?
Publicado por: Zaelsius en 09 de Abril de 2007, 05:51:07 PM
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.
Título: ¿Cómo comparar digitos en un entero?
Publicado por: J_F_NASH en 10 de Abril de 2007, 01:42:20 PM
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.
Título: ¿Cómo comparar digitos en un entero?
Publicado por: shephiroth en 10 de Abril de 2007, 06:47:13 PM
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;
}
Título: ¿Cómo comparar digitos en un entero?
Publicado por: Pogacha en 10 de Abril de 2007, 07:03:37 PM
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); }