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

2 Answers

0 votes
#include <iostream>
#include <string>
#include <cmath>
 
int sumDigits(long long n) {
    int sum = 0;
     
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
     
    return sum;
}
 
bool checkHalvesSumEqual(long long n) {
    std::string s = std::to_string(std::abs(n));
    int length = s.length();
     
    // Check if the number of digits is not equal (i.e., odd)
    if (length % 2 != 0) {
        std::cout << "The number of digits is NOT even. It cannot be split into two halves: ";
        return false;
    }
     
    int half_length = length / 2;
 
    long long first_half_num = std::stoll(s.substr(0, half_length));
    long long second_half_num = std::stoll(s.substr(length - half_length));
 
    return sumDigits(first_half_num) == sumDigits(second_half_num);
}
 
int main() {
    long long num1 = 123456; 
    long long num2 = 123321; 
    long long num3 = 123123; 
    long long num4 = 123411; 
    long long num5 = 1234321;
    long long num6 = 12321; 
 
    std::cout << num1 << ": " << std::boolalpha << checkHalvesSumEqual(num1) << std::endl;
    std::cout << num2 << ": " << std::boolalpha << checkHalvesSumEqual(num2) << std::endl;
    std::cout << num3 << ": " << std::boolalpha << checkHalvesSumEqual(num3) << std::endl;
    std::cout << num4 << ": " << std::boolalpha << checkHalvesSumEqual(num4) << std::endl;
    std::cout << num5 << ": " << std::boolalpha << checkHalvesSumEqual(num5) << std::endl;
    std::cout << num6 << ": " << std::boolalpha << checkHalvesSumEqual(num6) << std::endl;
}
 
 
 
/*
run:
 
123456: false
123321: true
123123: true
123411: true
1234321: The number of digits is NOT even. It cannot be split into two halves: false
12321: The number of digits is NOT even. It cannot be split into two halves: false

*/

 

 



answered Dec 20, 2025 by avibootz
edited Dec 22, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <numeric> // accumulate

bool halvesSumEqual(long long n) {
    std::string s = std::to_string(std::llabs(n));

    if (s.size() % 2 != 0)
        return false;

    std::size_t half = s.size() / 2;

    auto sumDigits = [](const std::string& part) {
        return std::accumulate(part.begin(), part.end(), 0,
            [](int acc, char c) { return acc + (c - '0'); });
    };

    int left  = sumDigits(s.substr(0, half));
    int right = sumDigits(s.substr(half));

    return left == right;
}

int main() {
    long long nums[] = {123456, 123321, 123123, 123411, 1234321, 12321};

    for (auto n : nums) {
        std::cout << n << ": "
                  << std::boolalpha
                  << halvesSumEqual(n)
                  << "\n";
    }
}

 
 
/*
run:
 
123456: false
123321: true
123123: true
123411: true
1234321: false
12321: false

*/



answered Dec 23, 2025 by avibootz
...