Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 7, 2019 18:39
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/f8ebdf6b25b99148242b494618fd69f1 to your computer and use it in GitHub Desktop.
Save parzibyte/f8ebdf6b25b99148242b494618fd69f1 to your computer and use it in GitHub Desktop.
bool esNarcisista(int numero){
// Nota: to_string pertenece a std, la llamada normal sería std::to_string
string numeroComoCadena = to_string(numero);
double longitudDelNumero = numeroComoCadena.size();
double suma = 0;
// Recorrer cadena, carácter por carácter
for(int indice = 0; indice < longitudDelNumero; indice++){
//Convertir el carácter a entero
double cifraActual = numeroComoCadena[indice] - '0';
// Elevarlo a la potencia dada por la longitud
double 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 true;
}else{
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment