How to check if two halves of a number are equal in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strconv"
)

func halvesEqual(n int) bool {
    s := strconv.Itoa(n)
    length := len(s)

    if length%2 != 0 {
        return false // cannot split evenly
    }

    half := length / 2
    left := s[:half]
    right := s[half:]

    return left == right
}

func main() {
    testNumbers := []int{1212, 123123, 45454545, 123, 1213}

    for _, n := range testNumbers {
        if halvesEqual(n) {
            fmt.Printf("%d -> equal halves\n", n)
        } else {
            fmt.Printf("%d -> not equal\n", n)
        }
    }
}



/*
run:

1212 -> equal halves
123123 -> equal halves
45454545 -> equal halves
123 -> not equal
1213 -> not equal

*/

 



answered Dec 22, 2025 by avibootz
...