Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

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

2 Answers

0 votes
def sum_digits(n: int) -> int:
    n = abs(n)
    total = 0
    while n != 0:
        total += n % 10
        n //= 10
    return total


def check_halves_sum_equal(n: int) -> bool:
    s = str(abs(n))
    length = len(s)

    if length % 2 != 0:
        print("The number of digits is NOT even. It cannot be split into two halves: ", end="")
        return False

    half = length // 2

    first_half = int(s[:half])
    second_half = int(s[-half:])

    return sum_digits(first_half) == sum_digits(second_half)


def main():
    nums = [
        123456,
        123321,
        123123,
        123411,
        1234321,
        12321
    ]

    for n in nums:
        print(f"{n}: {str(check_halves_sum_equal(n)).lower()}")


if __name__ == "__main__":
    main()



'''
run:

123456: false
123321: true
123123: true
123411: true
The number of digits is NOT even. It cannot be split into two halves: 1234321: false
The number of digits is NOT even. It cannot be split into two halves: 12321: false

'''

 



answered Dec 23, 2025 by avibootz
0 votes
def halves_sum_equal(n: int) -> bool:
    s = str(abs(n))
    if len(s) % 2 != 0:
        return False

    half = len(s) // 2
    left = s[:half]
    right = s[half:]

    return sum(map(int, left)) == sum(map(int, right))


nums = [123456, 123321, 123123, 123411, 1234321, 12321]

for n in nums:
    print(n, halves_sum_equal(n))




'''
run:

123456 False
123321 True
123123 True
123411 True
1234321 False
12321 False

'''

 



answered Dec 23, 2025 by avibootz
...