How to check if the sum of two halves of a number is equal in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
    "strconv"
)

func halvesSumEqual(n int64) bool {
    s := strconv.FormatInt(int64(math.Abs(float64(n))), 10)

    if len(s) % 2 != 0 {
        return false
    }

    half := len(s) / 2

    left := s[:half]
    right := s[half:]

    sumDigits := func(str string) int {
        sum := 0
        for _, ch := range str {
            sum += int(ch - '0')
        }
        return sum
    }

    return sumDigits(left) == sumDigits(right)
}

func main() {
    nums := []int64{123456, 123321, 123123, 123411, 1234321, 12321}

    for _, n := range nums {
        fmt.Printf("%d: %v\n", n, halvesSumEqual(n))
    }
}



/*
run:

123456: false
123321: true
123123: true
123411: true
1234321: false
12321: false

*/

 



answered Dec 23, 2025 by avibootz
...