Created
August 7, 2019 22:17
-
-
Save parzibyte/8df9c2581923ba9fe91d981b30ce469a to your computer and use it in GitHub Desktop.
Número narcisista en Golang - https://parzibyte.me/blog/2018/10/02/comprobar-si-es-numero-narcisista-en-go/
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 Go/Golang | |
parzibyte.me/blog | |
*/ | |
package main | |
import( | |
"fmt" | |
"math" | |
"strconv" | |
) | |
func main(){ | |
/* | |
Aquí probamos un arreglo de números, la función está más abajo | |
*/ | |
numeros := []int{1, 2, 3, 4, 153, 28, 11, 96, 407, 1634, 54748} | |
for _, numero := range numeros{ | |
fmt.Printf("¿%d es narcisista? %t\n", numero, esNarcisista(numero)) | |
} | |
} | |
// Aquí la función | |
func esNarcisista(numero int) bool{ | |
numeroComoCadena := strconv.Itoa(numero) | |
longitudDeNumero := len(numeroComoCadena) | |
suma := 0 | |
for indice := 0; indice < longitudDeNumero; indice++{ | |
// Convertir carácter a entero | |
cifraActual := numeroComoCadena[indice] - '0' | |
/* | |
Elevarlo al exponente dado por la longitud del número | |
por cierto, se castea a float64 porque math.Pow necesita un float64 | |
*/ | |
elevado := math.Pow(float64(cifraActual), float64(longitudDeNumero)) | |
// Vamos sumando el resultado | |
suma = suma + int(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