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,971 questions

51,913 answers

573 users

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

1 Answer

0 votes
import Foundation

func halvesSumEqual(_ n: Int) -> Bool {
    let s = String(abs(n))

    guard s.count % 2 == 0 else {
        return false
    }

    let half = s.count / 2
    let leftIndex = s.index(s.startIndex, offsetBy: half)

    let left = s[..<leftIndex]
    let right = s[leftIndex...]

    func sumDigits(_ part: Substring) -> Int {
        part.reduce(0) { $0 + Int(String($1))! }
    }

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

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

    for n in nums {
        print("\(n): \(halvesSumEqual(n))")
    }
}

main()



/*
run:

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

*/

 



answered Dec 23, 2025 by avibootz
...