Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created July 29, 2019 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/1673036840b9dfe701240ece02455b96 to your computer and use it in GitHub Desktop.
Save parzibyte/1673036840b9dfe701240ece02455b96 to your computer and use it in GitHub Desktop.
int esNarcisista(int numero) {
// Obtener longitud sin convertir a cadena
int longitudDelNumero = floor(log10(numero)) + 1;
// Búfer para alojar cadena
char numeroComoCadena[longitudDelNumero + 1];
// Convertir número a cadena
sprintf(numeroComoCadena, "%d", numero);
int suma = 0;
// Recorrer cadena, carácter por carácter
for (int indice = 0; indice < longitudDelNumero; indice++) {
// Convertir el carácter a entero
int cifraActual = numeroComoCadena[indice] - '0';
// Elevarlo a la potencia dada por la longitud
int elevado = pow(cifraActual, longitudDelNumero);
// Sumar el resultado a suma
suma = suma + elevado;
}
// Si la suma y el número recibido son iguales, es narcisista
if (suma == numero) {
return 1;
} else {
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment