Created
August 7, 2019 18:39
-
-
Save parzibyte/6cd75521ed48ed42f30e4aae23cb2091 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Determinar si un número es narcisista usando C++ | |
parzibyte.me/blog | |
*/ | |
#include <iostream> | |
#include <math.h> | |
using namespace std; | |
// Prototipo | |
bool esNarcisista(int numero); | |
int main(){ | |
// Algunos números para probar | |
int numeros[] = {1, 2, 3, 4, 153, 28, 11, 96, 407, 1634, 54748}; | |
for(int x = 0; x < sizeof(numeros) / sizeof(numeros[0]); x++){ | |
printf("%d es narcisista? %s\n", numeros[x], esNarcisista(numeros[x]) ? "true": "false"); | |
} | |
} | |
// función | |
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