Created
August 7, 2019 22:19
-
-
Save parzibyte/2152562abef0a8eed59c660e7f8dcdc9 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 | |
*/ | |
using System; | |
class Ejercicio{ | |
public static void Main(){ | |
// Probar con algunos números | |
int[] numeros = {1, 2, 3, 4, 153, 28, 11, 96, 407, 1634, 54748}; | |
foreach(int numero in numeros){ | |
Console.WriteLine("¿El número {0} es narcisista? {1}", numero, EsNarcisista(numero)); | |
} | |
} | |
// Justo aquí está la función | |
public static Boolean EsNarcisista(int numero){ | |
string numeroComoCadena = numero.ToString(); | |
int longitudDelNumero = numeroComoCadena.Length; | |
double suma = 0; | |
// Recorrer toda la cadena carácter por carácter, y elevarlo a la potencia | |
// dada por la longitud del número | |
for(int indice = 0; indice < longitudDelNumero; indice++){ | |
char caracterActual = numeroComoCadena[indice]; | |
int cifraComoEntero = (int) Char.GetNumericValue(caracterActual); | |
double numeroElevado = Math.Pow(cifraComoEntero, longitudDelNumero); | |
suma = suma + numeroElevado; | |
} | |
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