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 TypeScript

1 Answer

0 votes
function halvesSumEqual(n: number): boolean {
  const s: string = Math.abs(n).toString();

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

  const half: number = s.length / 2;

  const left: string = s.slice(0, half);
  const right: string = s.slice(half);

  const sumDigits = (str: string): number =>
    [...str].reduce((sum, ch) => sum + Number(ch), 0);

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


const nums: number[] = [123456, 123321, 123123, 123411, 1234321, 12321];

for (const n of nums) {
  console.log(`${n}: ${halvesSumEqual(n)}`);
}



/*
run:

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

*/

 



answered Dec 23, 2025 by avibootz
...