# Is it a balanced number?

A number is balanced if the sum of the digits on each half of the number is equal, so: 1423 is balanced because 1+4 = 2+3, so is: 42615 because 4+2=1+5. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

Challenge:

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

Test cases (true)

1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088


Test cases (false)

10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454


There will not be numbers starting with zero, for instance 00032 instead of 32. You must support numbers up to at least 100 digits (so larger than 2^64-1). As always, optional input format, so you may surround the number with apostrophes if desired.

# 05AB1E, 14 7 bytes

€D2äOQ


Explanation

Using 141 as example:

€D       # duplicate each (turns the number into a list of digits)
# STACK: ['1','1','4','4','1','1']
2ä     # split list in 2 (as we duplicated each element,
# the middle element will exist on both sides for an odd length input
# STACK: [['1','1','4'],['4','1','1']]
O    # sum each sublist
# STACK: [6,6]
# flatten
# STACK: 6, 6
Q  # compare for equality
# STACK: 1 (true)


Try it online!

• Can't you use Ë instead of Q? – Erik the Outgolfer Jul 11 '17 at 19:33
• @EriktheOutgolfer: Ë was a different command back when this challenge was made, so unfortunately not. – Emigna Jul 11 '17 at 19:57

# ><>, 31 29 bytes

i:0(?v
~00}v>
v+r+>l4(?
>{=n;


Try it online!

Line 1: Standard input loop

Line 2: Discard the -1 on top of the stack, push two 0's and rotate one to the bottom of the stack (this ensures that inputs of length <3 don't exhaust the stack later in the program)

Line 3: If the length of the stack is >3, add the top two and bottom two elements of the stack together.

Line 4: If top and bottom of the stack are equal, output 1, 0 otherwise.

Edit: realised that there's no need to take the characters mod 12, 2 bytes saved

b(a:t@(r:s))=a-last t+b(init t);b _=0


One Byte Saved thanks to nimi

• Don't snippets need parentheses? – Michael Klein Sep 23 '16 at 16:45
• @michael-klein No, unnamed function are allowed. meta.codegolf.stackexchange.com/a/7615/20260 – Damien Sep 23 '16 at 16:59
• One byte to save: b(a:t@(r:s))=a-last t+b(init t);b _=0 – nimi Sep 23 '16 at 17:23
• @nimi Thanks... – Damien Sep 24 '16 at 8:32

# Brachylog, 20 bytes

@eL@2tM,Lr@2t:M:+a#=


Try it online!

### Explanation

@eL                    Get the list of digits L of the input
L@2tM,               Get the second half M of L
Lr@2t          Get the second half of the reverse of L
:M        The list [L, M]
:+a#=   The sum of elements of L and the sum of elements of M must be equal


# Java, 85 bytes

n->{int s=0,i=0,l=n.length();for(;i<l/2;)s+=n.charAt(i)-n.charAt(l-++i);return s==0;}


Note: the input is given as String as Java can't handle without BigInteger (and BigIntegers are constructed using a... String.)

## Testing and ungolfed:

import java.util.function.Predicate;

public class Main {

public static void main(String[] args) {
Predicate<String> f = n -> {
int s = 0, i = 0, l = n.length();
for (; i < l / 2;) {
s += n.charAt(i) - n.charAt(l - ++i);
}
return s == 0;
};

String[] truthies = {"1",
"6",
"11",
"141",
"23281453796004414",
"523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088"};
for (String s : truthies) {
boolean result = f.test(s);
System.out.println(result);
}
String[] falsies = {"10",
"12",
"110",
"15421",
"5234095123508321",
"6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454"};
for (String s : falsies) {
boolean result = f.test(s);
System.out.println(result);
}
}
}

• Nice answer. You could save 2 bytes by making the for-loop empty: for (; i < l / 2;s += n.charAt(i) - n.charAt(l - ++i));. – todeale Sep 24 '16 at 7:31
• @todeale Look at the golfed code, not the ungolfed one. I think your suggestion and my golfed answer use the same amount of bytes – Olivier Grégoire Sep 24 '16 at 7:48
• Ooops! Now I see. – todeale Sep 24 '16 at 9:26

## Mathematica, 57 bytes

Tr@(#-Reverse@#)[[;;⌊Length@#/2⌋]]==0&@*IntegerDigits


### Explanation

I was really hoping I could use this approach in some language, and it seems to be doing fairly well in Mathematica. The idea is to avoid having to obtain both the front and the back half by combining the list with its reverse and looking only at the front half.

...&@*IntegerDigits


First, we turn the input into a list of decimal digits and pass the result to the unnamed function on the left.

...(#-Reverse@#)...


Now we subtract the reverse of the list from the list itself. If the digits are {a1,a2,...,an} then the result will be {a1-an,a2-an-1,...,an-a1}.

...[[;;⌊Length@#/2⌋]]


We extract the first half of this list (excluding the middle digit although that doesn't actually matter, because the corresponding difference will be 0 anyway).

Tr@...


And then we sum this list. So that's:

a1 - an + a2 - an-1 + ... + a⌊n/2⌋ - a⌈n/2⌉+1

Rearranging:

a1 + a2 + ... + a⌊n/2⌋ - (a⌈n/2⌉+1 + ... + an-1 + an)

The input is balanced if the two halves have the same sum. Hence, this expression is zero if the input is balanced. So that's what we check:

...==0


# JavaScript (ES6), 59555144 42 bytes

f=([x,...a],n=0)=>a?f(a,x-a.pop()+n):!n


Turns out I was using the wrong strategy entirely. This version recursively finds the sum of the first half minus the sum of the second half, then returns the logical NOT of the result.

If we could return falsy in place of truthy and vice-versa, this would be 35 bytes:

f=([x,...a])=>a?x-a.pop()+f(a):0


### Test snippet

f=([x,...a],n=0)=>a?f(a,x-a.pop()+n):!n
<input id=I value="23281453796004414"><br>
<button onclick="console.log(Result of f(${I.value}): +f(I.value))">Run</button> • I really like this n[i*2]! Nice one. – Arnauld Sep 23 '16 at 16:39 • @Arnauld Thanks :-) I've found a completely different approach now that doesn't need that at all... – ETHproductions Sep 23 '16 at 16:40 • Now, that's brilliant! – Arnauld Sep 23 '16 at 17:06 • Can't you use f=([x,...a])=>!(a?x-a.pop()+f(a):0)? – mbomb007 Sep 23 '16 at 18:46 • @mbomb007 Nope; that would return a boolean (coerced to 0 or 1) after every recursion, rather than a sum. – ETHproductions Sep 23 '16 at 21:55 ## PowerShell v2+, 85 bytes param($a)!((,'('+$a[0..(($b=$a.length)/2-1)]+'0)-('+$a[($b/2)..$b]+'0)')-join'+'|iex)


Takes input $a as a string (necessary to support numbers >2^64-1 without getting into extremely clunky [biginteger] casting on the command line). For the explanation, let's assume input of '1423'. We're then constructing a new string. The two array slices are obvious ($a[...]), and that's surrounded by three additional strings (, 0)-(, and 0), formulating an array of chars and strings. Note the , at the front to enforce array concatenation, not string concatenation.

That whole array is -joined together with +, resulting in a string like (+1+4+0)-(+2+3+0), and you can see that the 0s are needed to prevent syntax errors. That's fed into |iex (short for Invoke-Expression and similar to eval), which will compute the mathematical result. So long as the string is balanced, you'll get 0 as an output, which we encapsulate in parens and take the Boolean-not thereof !(...), to output True. If it's any non-zero integer, it'll output False.

### Test Cases

PS C:\Tools\Scripts\golfing> '1','6','11','141','23281453796004414','523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088'|%{$_;.\is-it-a-balanced-number.ps1$_;'---'}
1
True
---
6
True
---
11
True
---
141
True
---
23281453796004414
True
---
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
True
---

PS C:\Tools\Scripts\golfing> '10','110','15421','5234095123508321','6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454'|%{$_;.\is-it-a-balanced-number.ps1$_;'---'}
10
False
---
110
False
---
15421
False
---
5234095123508321
False
---
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
False
---


# Perl, 29 bytes

Includes +5 for -lpF

Give number on STDIN

balanced.pl <<< 1423


balanced.pl:

#!/usr/bin/perl -lpF
$;+=$_-pop@F for@F;$_=!$


# C#, 83 bytes

n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};


Try it online!

Full source, including test case:

using System;
using System.Numerics;

namespace BalancedNumber
{
class Program
{
static void Main(string[] args)
{
Func<BigInteger,bool>s= n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};

Console.WriteLine(s(1));    //true
Console.WriteLine(s(6));    //true
Console.WriteLine(s(11));   //true
Console.WriteLine(s(141));  //true
Console.WriteLine(s(23281453796004414));    //true
BigInteger bi = BigInteger.Parse("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088");
Console.WriteLine(s(bi));   //true
Console.WriteLine(s(10));   //false
Console.WriteLine(s(12));   //false
Console.WriteLine(s(110));  //false
Console.WriteLine(s(15421));    //false
Console.WriteLine(s(5234095123508321)); //false
bi = BigInteger.Parse("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454");
Console.WriteLine(s(bi));   //false
}
}
}


The BigInteger data type allows any number length. If the number is too large, the compiler complains (error CS1021: Integral constant is too large), so the BigInteger.Parse(String) method is used instead.

The solution can actually be reduced to 72 bytes considering the input is a string (and updating the program accordingly):

t=>{int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};

• Not surprisingly, my c answer ended up looking fairly similar to this one. Can you do t[l-++i] instead of t[l-1-i++], and return !r instead of return r==0? – Digital Trauma Sep 23 '16 at 17:04
• Prefixing the increment operator should do the trick and save 2 bytes, but in C# the return value must be a boolean, so !r won't cut it. Thanks, I'll update my answer as soon as possible. – adrianmp Sep 23 '16 at 18:08

## Python 3, 107102 76 bytes

n=input()
l=len(n)
print(sum(map(int,n[:l//2]))==sum(map(int,n[l//2+l%2:])))


-26 bytes by @Rod!

• you can replace floor(l/2) with l//2 and ceil(l/2) with l//2+l%2 to save 7 bytes, and then remove the math import, saving more 18 – Rod Sep 23 '16 at 13:58
• also you don't need the 0 on n[0:l//2] and n[l//2+l%2:] could just be n[-(l//2):]. Or you could move the //2 to l=len(n)//2 and use n[:l] and n[-l:] – Rod Sep 23 '16 at 14:26
• It also looks really weird when your import isn't at the top. – mbomb007 Sep 23 '16 at 14:33
• @Rod I came here to change all the things you mentioned on the first comment, but was amazed by the second one, thanks a lot! :) – Yytsi Sep 23 '16 at 20:48
• @Rod By using your last tip on your second comment, the single digit testcases return falsey values :( – Yytsi Sep 23 '16 at 20:59

## Ruby, 63 bytes

->s{e=s.chars*?+
l=s.size
e[l-1-r=l%2,2*r+1]="=="
l<2||eval(e)}


Note: arg s must be string.

### Testing(minitest 5+ required):

require 'minitest/autorun'

class TestRunner < Minitest::Test
def setup
@truthy_nums = %w(1 6 11 141 23281453796004414 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088)
@falsy_nums = %w(10 110 15421 5234095123508321 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454)

@f=->s{e=s.chars*?+
l=s.size
e[l-1-r=l%2,2*r+1]="=="
l<2||eval(e)}

end
def test_true
@truthy_nums.each do |e|
assert @f[e], e
end
end
def test_false
@falsy_nums.each do |e|
assert !@f[e], e
end
end
end


g(h:t)=read[h]-g(reverse t)
g _=0
(==0).g.(<*"xx").show


The recursive function g unwraps a number string from both ends by repeatedly taking the head, then reversing. It subtracts the recursive result from the head, which causes it alternate coefficients of +1 and -1, with +1 applied to the first half and -1 to the second half.

   g "12345"
== 1 - g "5432"
== 1 - (5 - g "432")
== 1 - (5 - (4 - g "32"))
== 1 - (5 - (4 - (3 - g "2"))
== 1 - (5 - (4 - (3 - 2))
== 1 + 2 + 3 - 4 - 5


So, it takes the sum of the first half minus the sum of the second half. This has the issue that with an odd number of digits, the center tiebreaks to the left, but the main function fixes that by (<*"xx"), which doubles every character, i.e. "12345" becomes "1122334455". That way the middle digit splits evenly on both sides and cancels out.

# Retina, 64 44 bytes

^((.)*?).?(?=(?<-2>.)*$)$1
\d
$* ^(1+) \1$


Try it online

The first stage splits the string in the middle, omitting the middle character if there is one (taken and modified from here. Courtesy of Martin.) Then, replace digits with their unary representation, and match if the two halves are of equal length.

• Why would you use a non-capturing group in a code golf? ;) Regardless, in .NET it's much shorter to split the string with balancing groups: retina.tryitonline.net/… (I also tried multiple stages but that ends up slightly longer retina.tryitonline.net/…). – Martin Ender Sep 23 '16 at 14:58
• @MartinEnder Yeah, I knew it would be, but I never really grasped the concept. And I suppose I overlooked the non-capturing group. – mbomb007 Sep 23 '16 at 15:11
• It's really simple in this case: we count characters with (.)*? (each iteration pushes a capture onto stack 2). Then we try to reach the end by popping from the stack again with (?<-2>.)*$ (after an optional middle digit). The first time this is possible is when we've captured exactly half the digits (rounded down) into group 2. – Martin Ender Sep 23 '16 at 15:15 ## JavaScript (ES6), 7467 ... 59 50 bytes Recursively sums the difference of the first and last digits until there's less than two digits left: let f = n=>!(F=n=>n?(n.pop()-n.shift()+F(n)):0)([...n]) // some truthy examples console.log(f("11")); console.log(f("141")); console.log(f("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088")); // some falsy examples console.log(f("12")); console.log(f("110")); console.log(f("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454")); • Nice technique. I think you can do (s-=i<0?v:-v). – ETHproductions Sep 23 '16 at 15:18 • @ETHproductions - Interesting to see how close the methods with and without Math.sign() turn out to be. – Arnauld Sep 23 '16 at 16:13 • Darn, you may have beaten me for good... nice one :) – ETHproductions Sep 23 '16 at 16:55 • I was wrong ;-) – ETHproductions Sep 23 '16 at 17:00 # R, 105 96 bytes Turns out R is very verbose. Takes input as a character. function(x){y<-as.numeric(unlist(strsplit(x,"")));l<-length(y)%/%2;sum(tail(y,l))==sum(head(y,l))}  Formatted nicely: function(x){ y=as.numeric(unlist(strsplit(x,""))) l=length(y)%/%2 sum(tail(y,l))==sum(head(y,l)) }  Explanation • y<-as.numeric(unlist(strsplit(x,""))) Split the input (a string_, and coerce it to a vector instead of a list, and then turn it back into integers. • sum(tail(y,: tail takes the last n elements, found by: • length(y)%/%2)), where %/% is integer division, to get the ceiling of the quotient, where the length is odd. • sum(head(y,length(y)%/%2)): like tail, head takes the first n elements of the vector, found in the same way. ## Edits • Saved seven bytes thanks to niam • Switched to = instead of <- , saved another two bytes. • Can you bind length(y)%/%2 somehow to a variable and use that within the calls of tail and head? – nimi Sep 23 '16 at 17:51 • @nimi Oh yeah, good point. – Azor Ahai Sep 23 '16 at 17:53 • 85 bytes tio.run/… – Sumner18 Dec 14 '18 at 17:50 • by consolidating y and l into the first sum, changing as.numeric to as.double(), unlist() to el(). This allowed me to do it all in one line, removing brackets, and pryr::f guesses the formals/variables from the code – Sumner18 Dec 14 '18 at 17:56 # Brain-Flak, 410206204 178 + 3 = 181 bytes Here is a 178 byte version that uses the -a flag. 26 bytes golfed off by DJMcMayhem Try it Online ([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>){({}[()]<({}<>)<>>)}{}([]<>[[]]<>){(<{}{}>)}{}({{}<>[{}]<>}<(())>){{}{}((<>))}{}  Here is a longer 410 byte version that does not use the -a flag. Try it Online {(({}))(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}>)<>(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)}{}<>([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>){({}[()]<({}<>)<>>)}{}([]<>[[]]<>){{}{}(<>)}{}(([])<>)({<{}>{}<([])>}{}<>[{<{}>{}<([])>}{}]<(())>){{}{}((<>))}{}  # Explanation Here is an explanation of the shorter solution To begin the number is converted to all of its ASCII values by the -a flag. We push the stack height (i.e. number of digits) and divide by two. ([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)  For each number less than the number we just pushed we move a digit to the other stack {({}[()]<({}<>)<>>)}{}  If the stacks have different heights we remove the top item from the current stack ([]<>[[]]<>){(<{}{}>)}{}  We want the difference between the sums of each stack. So we use the following algorithm to sum each stack. {{}}  This assumes no digit has an ASCII value of zero, which is a valid assumption. We run this for both stacks and take the difference (The <(())> is necessary for the next part. ({{}}<>[{{}}]<(())>)  We now want to negate the sum. If the sum is zero it will pop the top off revealing the one we pushed earlier otherwise it will remove both the number and the one and place a zero on top. {{}{}((<>))}{}  • Why use ([]){[{}]{}([])}{} to sum each stack? ({{}}) should work just fine, and since you're taking ASCII input, you don't have to worry about 0's ruining the loop. – DJMcMayhem Sep 23 '16 at 18:19 • @DJMcMayhem Good point. I forgot there couldn't be a zero on the stack – Sriotchilism O'Zaic Sep 23 '16 at 18:49 # Actually, 17 16 bytes This answer is inspired by ElPedro's Python 2 answer and their idea to use [-b:]. Golfing suggestions welcome. Try it online! $♂≈;l½L│±aHΣ)tΣ=


Ungolfing

      Implicit input n.
$♂≈ list(str(n)). This converts n to a list of n's digits. ;l Duplicate the list of digits and get its length. Call it len. ½L Push len//2. │ This duplicates the stack. Stack: len//2, digit_list, len//2, digit_list ± Negate the len//2 at TOS for later. a Invert the stack. Stack: digit_list, len//2, digit_list, -(len//2) HΣ Push digit_list[:len//2], then push its sum. ) Rotate this first sum to BOS. tΣ Push digit_list[-(len//2):], then push its sum. = Check if those sums are equal. Implicit return.  # Perl 6, 42 39 33 bytes {[==] .comb[{^($_/2),Int($_/2)..*}]>>.sum}  Test it {[==] .comb[^(*/2),(*/2).Int..*]>>.sum}  Test it {[==] .comb[^*/2,^*/2+*/2]>>.sum}  Test it (from Jo King) ## Explanation: { # lambda with implicit parameter ｢$_｣

[==]                   # reduce the following using &infix:«==»

.comb\               # split input into individual characters
[                    # index into that using:

# first half of the values (includes middle value)
# ｢(0/2) ..^ (*/2)｣
^ * / 2,

# last half of the values (includes middle value)
^ * / 2            # same number of values as first half
+ * / 2          # shifted up by half

]\
>>.sum               # sum each of the two halves separately
}

• This doesn't seem to work anymore (I suspect a change in how .. handles non-integers). How about 33 bytes instead – Jo King Aug 1 '18 at 4:06

# Javascript, 73 bytes

Good ol' ES5 loops

for(a=c=0,b=(l=(s=prompt()).length)-1;a<~-l/2;c-=s[a++]-s[b--]);alert(!c)

What's happening here?

for(
a=c=0,               // a = left digits of the number
// c = the result
b=                   // b = right digits of number
(l=              // l = length of number - 1
(s=prompt()) // s = the number as input from user
.length)-1;

a<~-l/2;             // while a < length of number / 2, rounded down (~-)

c-=
s[a++]           // c -= left digit
-
s[b--]           // c += right digit (because - and - == +)
);
// for balanced numbers c should be 0
alert(!c)               // 0 equals false in javascript, so output the opposite of c


# Python 2, 73 bytes

def f(n):x=map(int,str(n));d=len(x)/2;print sum(x[:d])==sum(x[-d:])or d<1


Tests are at ideone

We have to use str() rather than  since n may be outside the range of signed int.

• Ah, that's why I was getting the L at the end. +1 – ElPedro Sep 24 '16 at 6:16

# Python 2, 83 77 bytes

g=[int(h)for h in raw_input()];b=int(len(g)/2);print sum(g[:b])==sum(g[-b:])or b==0


EDIT

reduced to 77 with help from @Rod

g=[int(h)for h in raw_input()];b=len(g)/2;print sum(g[:b])==sum(g[-b:])or b<1


Examples:

D:\>bal.py
1
True

D:\>bal.py
6
True

D:\>bal.py
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
True

D:\>bal.py
10
False

D:\>bal.py
110
False

D:\>bal.py
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
False

• you can use map(int,input()) instead [int(h)for h in raw_input()], len(g)/2 will always be int, no need to convert, and or b==0 ins't really necessary – Rod Sep 23 '16 at 14:34
• in fact the b==0 is needed for len=1, but you can shorten it to b<1 – Rod Sep 23 '16 at 14:45

# PHP, 736760 57 bytes

Requires PHP 7.1 for negative string offsets:

for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;  Run: echo 15324 | php -nR 'for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;';echo


# Previous version

Note: requires PHP 7 for the spaceship operator.

for(;$x<$l=strlen($a=$argv);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;


Run like this:

php -d error_reporting=30709 -r 'for(;$x<$l=strlen($a=$argv);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;' -- 15324;echo


## Explanation

Iterates over the digits in the number. Checks if the digit belongs to the first half or the second half (or is the middle digit) by comparing the digit's index to the length of the input with combined comparison (2 * $x <=>$l - 1). Then multiply that with the digit, take the sum of all digits. If it's a balanced number, the sum will be 0.

Example with input 15324:

  index     0  1  2  3  4
digit     1  5  3  2  4

2*index   0  2  4  6  8
length-1  4  4  4  4  4
factor    1  1  0 -1 -1  # Result of the spaceship operator

result    1  5  0 -2 -4
--------------
sum                   0


# Tweaks

• Don't set the digit to $d, just iterate the length of the input. Saved 5 bytes. • String offset null doesn't have to be cast to int for PHP to interpret it as 0. Saved 1 byte. • Using negative string offsets to get the digits from the second half and iterating to half of the string. Saved 7 bytes, but requires PHP 7.1 • Saved 3 bytes by using $argn

## Clojure, 66 64 bytes

Update: Took str out from the map int function.

(comp #(=(apply +(map -(drop(/(count %)2)%)%))0)#(map int %)str)


This would have been shorted if the input format was more flexible, now I had to first map the integer into a sequence of ASCII values. The inner map calculates pair-wise differences of values from the two halves, and this checks if the sum of deltas is zero.

((comp f g h) x y z) = (f (g (h x y z)).

Actually this ended up being the same length as just doing the mapping within a let and just define a single function.

# sed (165 + 1 for -r) 166

/^.$/c1 :l;s,^([^!])([^!]*)([^!])!?([^=]*)=?(.*),\2!\4\1=\5\3,;tl;: s,.?!|0,,;s,2,11,;s,3,21,;s,4,31,;s,5,41,;s,6,51,;s,7,61, s,8,71,;s,9,81,;t;s,1=1,=,;t;/^=$/c1
c0


Output:
1 for true
0 for false

Try it online!

# Python 2.7, 102 92 bytes

For loop works better :/

s=input()
a,b,l=0,0,len(s)
for i in range(l/2):a=a+int(s[i]);b=b+int(s[l-i-1])
print a==b


Same idea, just use length - i to get other side. It will never reach the center of an odd number.

Old code

s=input()
l=len(s)
def n(i):return 0if not i else int(i)+n(i[1:])
print n(s[:l/2])==n(s[l/2+l%2:])


Gets input
Saves length of input
Recursive func to get sum of string
Compare the first half sum to the second half sum

Trying to get it below 100, but its hard :/

# C function, 74

l;i;t;f(char *n){l=strlen(n);for(t=i=0;i<l/2;)t+=n[i]-n[l-++i];return !t;}


Ideone.

• You can't use strlen without including #include"string.h"\n, which adds 19 to your score. – NoSeatbelts Sep 30 '16 at 16:31
• @NoSeatbelts Yes you can - try out the Ideone link. The compiler will most likely give you a bunch of warnings, but compile a working executable anyway (at least GCC and Clang do). Which compiler are you using? There's even a code-golf tip about this. – Digital Trauma Sep 30 '16 at 17:14
• No need for the space in char *n – Cyoce May 6 '17 at 20:51
• remove spaces l;i;t;f(char*n){..return!t;} -2 bytes – Khaled.K May 7 '17 at 17:32

## Racket 204 bytes

(define(f n)(let*((s(number->string n))(g(λ(x y)(apply +(map(λ(x)(string->number(string x)))
(string->list(substring s x y))))))(l(string-length s))(h(/ l 2)))(if(=(g 0(floor h))(g(ceiling h)l))#t #f)))


Detailed version:

(define (f1 n)
(let* (  (s (number->string n))
(g(λ(x y)
(apply + (map
(λ(x)
(string->number
(string x)))
(string->list
(substring s x y))))))
(l (string-length s))
(h (/ l 2)))
(if(= (g 0 (floor h)) (g (ceiling h) l))
#t #f  ) ) )


Testing:

(f 23281453796004414)
(f 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088)
(f 15421)
(f 5234095123508321)


Output:

#t
#t
#f
#f


## Pyke, 20 bytes

[QleQ)>[R<]mmbms\$X!


Try it here!

• @WeeingIfFirst you were right - I forgot not  was 0 not 1 – Blue Sep 23 '16 at 19:48

## Mathematica, 69

Tr@#[[;;⌊l=Length@#/2⌋]]==Tr@#[[⌈l⌉+1;;]]&@*IntegerDigits

• You can save a couple of bytes by changing the end to ...;;]]&@*IntegerDigits – Martin Ender Sep 23 '16 at 15:01
• @MartinEnder thanks, but how does this work? – shrx Sep 24 '16 at 7:32
• @* is short for Composition. f@*g is f[g[##]]&. – Martin Ender Sep 24 '16 at 7:44