Created
August 7, 2019 22:15
-
-
Save parzibyte/9415dfe8ea0fb3e7feaff6a14a42c695 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
class Narcisista{ | |
public static void main(String[] argumentos){ | |
int numeros[] = {1, 2, 3, 4, 153, 28, 11, 96, 407, 1634, 54748}; | |
for(int numero: numeros){ | |
System.out.println(numero + " es narcisista?" + esNarcisista(numero)); | |
} | |
} | |
private static boolean esNarcisista(int numero){ | |
String numeroComoCadena = Integer.toString(numero); | |
int longitudDeNumero = numeroComoCadena.length(); | |
double suma = 0; | |
for(int indice = 0; indice < longitudDeNumero; indice++){ | |
// Convertir carácter a entero | |
int cifra = Character.getNumericValue(numeroComoCadena.charAt(indice)); | |
/* | |
Elevarlo al exponente dado por la longitud del número | |
*/ | |
double elevado = Math.pow(cifra, longitudDeNumero); | |
// Vamos sumando el resultado | |
suma = suma + elevado; | |
} | |
// Finalmente comprobamos si el número es igual a la suma | |
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