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 Rust

1 Answer

0 votes
fn halves_sum_equal(n: i64) -> bool {
    let s = n.abs().to_string();

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

    let half = s.len() / 2;
    let (left, right) = s.split_at(half);

    let sum_digits = |part: &str| {
        part.chars()
            .map(|c| c.to_digit(10).unwrap() as i32)
            .sum::<i32>()
    };

    sum_digits(left) == sum_digits(right)
}

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

    for &n in nums.iter() {
        println!("{}: {}", n, halves_sum_equal(n));
    }
}



/*
run:

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

*/

 



answered Dec 23, 2025 by avibootz
...