Skip to content

Instantly share code, notes, and snippets.

@gerep
Created Dec 19, 2017
Embed
What would you like to do?
// Split the integer number into two (n is always even in size)
// Sum each half, if they are equal, return true
package main
import (
"fmt"
"strconv"
)
func main() {
x := 1230
fmt.Println(isLucky(x))
}
func isLucky(n int) bool {
str := strconv.Itoa(n)
// Get the length of n's half
size := len(str) / 2
// Tells the loop when to change the sum to the second half
counter := 0
var firstHalf int
var secondHalf int
for _, v := range str {
x, err := strconv.Atoi(string(v))
if err != nil {
fmt.Printf("Error converting %s into integer: %s", v, err)
}
if counter < size {
firstHalf = firstHalf + x
} else {
secondHalf = secondHalf + x
}
counter++
}
if firstHalf == secondHalf {
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment