# Calculate the sum of ILD

An integer

### Output:

Sum of the input itself + the length of the input + each individual digit of the input.

nr + nr-length + {sum of digits} = output


### Examples:

Input: 99
Output: 99 (nr) + 2 (nr-length) + (9 + 9) (digits) → 119

Input: 123
Output: 123 + 3 + (1 + 2 + 3)132

### Challenge rules:

• The input can also contain negative input, which are resolved special. The -/minus-sign is also +1 for the length, and is part of the first digit.
For example:

Input: -123
Output: -123 + 4 + (-1 + 2 + 3)-115

• You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

### General rules:

• This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
• Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
• Default Loopholes are forbidden.

### Test cases:

87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886


Semi-related: Count Sum of all Digits

• I think that with the negative numbers, for example -123 the sum chain should be (-1 + 1 + 2 + 3) instead of (-1 + 2 + 3), right? – Yytsi Jun 30 '16 at 16:36
• @TuukkaX Nope, it should be -1 + 2 + 3. For this challenge I choose to merge the -/minus-sign to the first digit as one negative digit to make it a bit more interesting. – Kevin Cruijssen Jun 30 '16 at 17:36

## 05AB1E, 282018 8 bytes

ÐgsS'+ýO


Explanation

Ð           # triplicate input
g          # get length of input
sS'+ý     # split input and merge with '+' as separator
O    # sum and implicitly display


Try it online

Saved 10 bytes thanks to @Adnan

• Luckily, 05AB1E does auto-evaluation on arithmetic expressions, so you can do this: ÐgsS'+ýO. – Adnan Jun 30 '16 at 9:17
• @Adnan: Nice! I didn't know that it did. – Emigna Jun 30 '16 at 9:26

# Python 2, 39 bytes

lambda x:x+len(x)+eval("+".join(x))


Test suite

Using the same eval-trick as in my Pyth-answer.

• I never used Python, so forget my possible ignorance, but how does the eval and join know to take the negative first digit for negative input? I would expect -123 to become something like - + 1 + 2 + 3 written out, but apparently it isn't.. (Or is it, and it automatically merged - + 1 to -1 as second step?) – Kevin Cruijssen Jun 30 '16 at 9:19
• @KevinCruijssen like you said -123 becomes "-+1+2+3" after joining which yields the correct result when you eval it. Try eval("-+1") for example which results in -1. – Denker Jun 30 '16 at 9:24
• @KevinCruijssen - + 1 -> - 1. The unary plus operator exists, so - + 1 is essentially the same as -(+(1)). +a is the same as a, for numbers. – Erik the Outgolfer Jun 30 '16 at 9:24

# Pyth, 11 10 bytes

Thanks to @LeakyNun for a byte!

++vj\+Ql


Test suite

## Explanation

++vj\+QlQQ  # Q = input, last two implicitly added

vj\+Q      # Join the input on '+' and eval it
lQ   # Length of the input
Q  # The input itself
++            # Add those three values to obtain the result


# CJam, 18

q_,\~__Ab(@g*\~]:+


Try it online

Explanation:

q_      read the input and make a copy
,\      get the string length and swap with the other copy
~__     evaluate the number and make 2 copies
Ab      convert to base A=10 (array of digits), it uses the absolute value
(       take out the first digit
@g*     get a copy of the number, get its sign and multiply with the digit
\~      dump the other digits on the stack


# Brachylog, 35 32 bytes

lL,?:ef+:?:L+I,(0>?h:2*:Ir-:1+.;I.)
lL,(0>?h:1--I;I0),?b:ef+:?:L:I+.


### Explanation

lL,             L is the length of the Input
(
0>?         Input < 0
h:1--I   I is (First digit - 1) * -1
;               Or
I0          I is 0
),
?b:ef+          Sum all digits of the Input
:?:L:I+.  Output = sum of digits + (Input minus first digit) + L + I


# XSLT 1.0 (without EXSLT), 673 bytes

<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"><output method="text"/><param name="i"/><template match="/"><variable name="d"><variable name="s">0<if test="0>$i">1</if></variable><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,$s+2)"/></call-template></variable><value-of select="substring($i,1,$s+1)+$d"/></variable><value-of select="$i+string-length($i)+$d"/></template><template name="d"><param name="i"/>0<if test="$i!=''"><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,2)"/></call-template></variable><value-of select="substring($i,1,1)+$d"/></if></template></transform>  Lightly inflated: <transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"> <output method="text"/> <param name="i"/> <template match="/"> <variable name="d"> <variable name="s">0<if test="0&gt;$i">1</if></variable>
<variable name="d">
<call-template name="d">
<with-param name="i" select="substring($i,$s+2)"/>
</call-template>
</variable>
<value-of select="substring($i,1,$s+1)+$d"/> </variable> <value-of select="$i+string-length($i)+$d"/>
</template>
<template name="d">
<param name="i"/>0<if test="$i!=''"> <variable name="d"> <call-template name="d"> <with-param name="i" select="substring($i,2)"/>
</call-template>
</variable>
<value-of select="substring($i,1,1)+$d"/>
</if>
</template>
</transform>


Run using xsltproc:

xsltproc --param i -87901 ild.xsl ild.xsl


Yes, ild.xsl is passed twice: Once as the XSLT document and then as the XML document to be transformed. An input document must be present because an XSLT processor generally requires one to begin running. (XSLT is designed to define a transformation from an input document to an output document; running a transform solely with command-line parameters as I've done here is atypical.) For this program, any well-formed XML document will suffice as input, and, XSLT being an application of XML, any well-formed XSLT transform is by definition a well-formed XML document.

• +1 for using something that totally isn't meant for calculating number and making it work anyway. – DJMcMayhem Jun 30 '16 at 18:48
• Can't you remove some quotes to make it "invalid but good for codegolf"? – Erik the Outgolfer Jul 1 '16 at 10:20
• Surely you don't need space after quotes in name="i" select="..." eg <with-param name="i"select="substring($i,$s+2)"/> ? – cat Jul 1 '16 at 14:33
• @cat There are only three of those in the entire document, and actually removing the space causes xsltproc to choke. – psmay Jul 1 '16 at 14:49
• @psmay Oh, that's weird. Erik was saying if you remove the quotes, it can be technically invalid according to the standard but still work properly like HTML, most implementations of which will render tags without quoted attribute values <p id=hello> etc. I guess if xsltproc cares about whitespace it won't let unquoted things by. – cat Jul 1 '16 at 14:52

# MATL, 20 bytes

tVtnw48-PZ}t0<?x_]vs


Try it Online

All test cases

Explanation

        % Implicitly grab the input
tV      % Duplicate the input and convert to a string
tn      % Duplicate and find the length of this string
w       % Flip the top two stack elements to get us the string again
48-     % Subtract 48 (ASCII 'O'). Yields a negative number for a negative sign
% and digits otherwise
P       % Flip the resulting array
Z}      % Break the array up so each element is pushed to the stack
t0<?    % If the first character was a negative sign
x_    % Pop the negative sign off the stack and negate the first digit
]       % End of if
vs      % Vertically concatenate and sum all stack contents
% Implicitly display the result


# Clojure, 102 bytes

(fn[n](load-string(str"(+ "n" "(count(str n))" "(apply str(map #(if(= % \-)%(str %" "))(str n)))")")))


Anonymous function which constructs a string that looks like (+ -123 4 -1 2 3 ) and evals it. Everything pretty verbose as it is, construct string from number, its length, and then map each symbol of string representation of the number except minus to itself plus space and minus remains the same

You can see it running here: https://ideone.com/FG4lsB

# Dyalog APL, 1917 16 bytes

≢+#⍎'\d'⎕R'&+',⊢


Takes string and returns

≢ length
+ plus
# in root namespace
⍎ evaluation of
'\d'⎕R'&+' regex append digits with a plus
, followed by
⊢ the unmodified string

–3 thanks to ngn

## Matlab, 76 67 bytes

n=input('');t=num2str(n)-48;if(n<0)t(1)=0;t(2)=-t(2);end
n+sum(t+1)


9 bytes saved thanks to @Luis Mendo

Explanation:

n=input('');     -- takes input
t=num2str(n)-48; -- makes it a string and then array of digits with "-" becoming -3 (48 is code for 0)
if(n<0)
t(1)=0;          -- set first element (-3) to 0
t(2)=-t(2);      -- the second element is the most significant digit, so we have to negate it
end
n+sum(t+1)       -- take sum of n, sum of all digits and length of t
(guaranteed by +1 of every element)

• sum(t+1)+n is shorter than sum([n numel(t) t]) – Luis Mendo Jul 1 '16 at 11:10
• Whoa, I spent a while thinking why this works. Great, thanks! – pajonk Jul 1 '16 at 13:13

# dc, 57 bytes

dc -e"0 1?rdsc*d[1r]s+d0>+dZr[+la10~lc*rdsaZ1<A]sAdsaZ1<Ala+++f"


Explained:

0 1      # Push 0, then 1 on the stack
?        # Wait for input from stdin
# If input is negative, the leading minus will subtract 1 from 0
r        # Swap (rotate) top two items on stack.
# Stack status if input ($') was... # positive negative # TOP 1 <- coefficient -> -1 #$                           $# 0 dsc # Store a copy of coefficient in c' * # Multiply input by coefficient: # If input was positive, it stays positive. # If input was negative, it's actually interpreted as positive. # In this case, multiply by -1 to make it negative. d # Duplicate signed input [1r]s+ # Define a function +': Push 1 and rotate d 0>+ # If input is negative, push 1 underneath the top of the stack # This 1 represents the length of the - in the input # Note that the stack now has 3 items on it, regardless of input sign dZ # Push the length of the input (not including leading minus) r # Rotate, moving a copy of the input to the top [ # Begin function definition + # Add top two items of stack la # Load value from a' (which holds nothing at time of function definition) 10~ # Slice the last digit off a' (spoiler: a' is going to hold the input while # we gather its digits) lc* # Multiply digit by coefficient # Since the input is signed, the input modulo 10 will have the same sign. # We want all digits to be positive, except the leftmost digit, which should # have the sign of the input. # This ensures that each digit is positive. r # Rotate: move remaining digits to top of stack dsa # Store a copy of the remaining digits in a' Z 1<A # Count the number of digits left; if more than 1, execute A ]sA # Store the function as A' d sa # Store a copy of the input in a' # Props to you if you're still reading this Z 1<A # Count the number of digits left; if more than 1, execute A la # Load leftmost digit of input (still signed appropriately) +++ # Add the top four items on the stack f # Dump stack  This was far more complicated than I had expected! Good challenge :) • I made a point of not looking at yours until mine was working to see if we had similar approaches... But I see you can get a byte back by swapping your 10~ for a A~! – brhfl Sep 20 '16 at 18:35 ## Bash + coreutils, 36 bytes bc<<<$1+${#1}+$(sed s:\\B:+:g<<<0$1)  Explanation: $1+                      # the input number (+)
${#1}+ # the length of the number, the '-' sign included (+)$(sed s:\\B:+:g<<<0$1) # insert '+' between two consecutive word characters #A word character is any letter, digit or underscore. bc<<< # calculate the sum  In sed, \B also matches between two consecutive non-word characters, so for a negative number it matches between '^' and '-'. Note the 0$1 trick needed for \B to give 0-1+2+3, for example.

Run example: 'input.txt' contains all the test cases in the question's statement

while read N;do echo "$N -> "$(./ILD_sum.sh "$N");done < input.txt  Output: 87901 -> 87931 123 -> 132 99 -> 119 5 -> 11 1 -> 3 0 -> 1 -3 -> -4 -99 -> -96 -123 -> -115 -900 -> -905 -87901 -> -87886  • @DigitalTrauma that won't work for negative integers. – seshoumara Sep 26 '16 at 6:48 • @DigitalTrauma Well, yes (but code size won't change) and no (if sed is left as is). The reason is that a backslash will be treated differently when using a command substitution with backticks compared to $(). There are two alternative ways to do it with backticks, but both give a 36 bytes solution in the end: sed 's:\B:+:g'<<<0$1 and sed s:\\\B:+:g<<<0$1. – seshoumara Sep 26 '16 at 17:20

## PowerShell v4, 48 bytes

param($n)$n,"$n".length+[char[]]"$n"-join'+'|iex


This should work in v2+, but I only tested in v4.

Takes input $n. Creates a new array with the , operator consisting of $n and the .length when $n is converted to a string. Concatenates with that the string $n cast as a char-array. Then, that whole array is -joined together with + before being piped to iex (similar to eval). The result is left on the pipeline and output is implicit.

For example, for input -123, the array would look like (-123, 4, -, 1, 2, 3), and the string after the -join would look like -123+4+-+1+2+3. Then the Invoke-Expression happens, and the result is -115 as expected.

# Factor with load-all, 175 bytes

Well, this is not very short. The special handling of unary minus is really annoying; I guess I could do it better and I will, maybe.

[ dup [ 10 >base length ] [ [ 10 >base >array [ 48 - ] V{ } map-as ] [ 0 < ] bi [ reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip ] [ ] if 0 [ + ] reduce ] bi + + ]


Using this substitution regex:

s/(-?[\d]+)\s*->\s*(-?[\d]+)/{ $2 } [$1 calculate-ild ] unit-test/g


We can turn the OP's test cases into a Factor test suite.

USING: arrays kernel math math.parser sequences ;
IN: sum-ild

: sum-digits ( n -- x )
[ number>string >array [ 48 - ] V{ } map-as ]
[ 0 < ]
bi
[
reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip
]
[ ] if
0 [ + ] reduce ;

: calculate-ild ( n -- x )
dup
[ number>string length ]
[ sum-digits ]
bi + + ;

USING: tools.test sum-ild ;
IN: sum-ild.tests

{ 87931 } [ 87901 calculate-ild ] unit-test
{ 132 } [ 123 calculate-ild ] unit-test
{ 119 } [ 99 calculate-ild ] unit-test
{ 11 } [ 5 calculate-ild ] unit-test
{ 3 } [ 1 calculate-ild ] unit-test
{ 1 } [ 0 calculate-ild ] unit-test
{ -4 } [ -3 calculate-ild ] unit-test
{ -115 } [ -123 calculate-ild ] unit-test
{ -905 } [ -900 calculate-ild ] unit-test
{ -87886 } [ -87901 calculate-ild ] unit-test


## C#, 118 bytes

int k(int a){var s=a.ToString();for(int i=0;i<s.Length;a+=s[i]<46?-(s[++i]-48)+ ++i-i:(s[i++]-48));return a+s.Length;}

• The fact you need the space in 1+ ++i is completely ridiculous imo – cat Jun 30 '16 at 23:04
• you're right but i didn't know how to do it without this... – ScifiDeath Jul 1 '16 at 4:28
• you can do s[i]<46 to check for minus – cliffroot Jul 1 '16 at 7:59
• @ScifiDeath Can't you do ++i+1? – Erik the Outgolfer Jul 1 '16 at 10:21
• @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ No, because of infix math's dumb order of evaluation – cat Jul 1 '16 at 14:29

1 INPUT a$: l=LEN a$: b$="text "+a$+"+"+STR$l+"+": FOR i=1 TO l: b$=b$+a$(i)+("+" AND i<l): NEXT i: EXECUTE b$ Builds up a string which then gets run. Unfortunately EXECUTE doesn't work with the ? shorthand for PRINT, but TEXT saved 1 character. # C#, 106 bytes I beat java my a byte, my life is complete int r(int n){var s=n+"";return n+s.Length+s.Select((k,j)=>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();}  Ungolfed (kinda)  public static int r(int n) { var s = n + ""; return n + s.Length + s.Select((k, j) =>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum(); }  • pretty sure you can replace string with var and '-' with 45 – ScifiDeath Jun 30 '16 at 22:23 • you can do (n)=>{.... for an anonymous lambda – cat Jul 1 '16 at 15:27 • cat could you elaborate? im trying to figure it out by myself but its not working for me. i never did that – downrep_nation Jul 1 '16 at 17:48 • I know it's been a while, but you can golf it to 89 bytes: n=>n+(n+"").Length+(n+"").Select((k,j)=>int.Parse((n+"")[k<48?1:j]+"")*(k<48?-2:1)).Sum() Although you'll have to add +18 for using System.Linq; which you also forgot in your current answer. – Kevin Cruijssen Feb 16 '18 at 15:41 # Java 8, 17413612210710593 78 bytes i->{int f=0;for(int j:(i+"").getBytes())i+=j<48?f++:f-->0?50-j:j-47;return i;}  -14 bytes thanks to @LeakyNun. -15 bytes thanks to @cliffroot. Explanation: Try it online. i->{ // Method with integer as both parameter and return-type int f=0; // Integer-flag, starting at 0 for(int j:(i+"").getBytes()) // Loop over the digits as bytes i+= // Increase the input with: j<48? // If the current byte is '-': f++ // Increase the input with the flag-integer f (which is 0), // and increase the flag-integer f by 1 afterwards : // Else: f-->0? // If the flag-integer f is 1, // and decrease the flag-integer f back to 0 afterwards 50-j // Increase it with 50 minus the current byte : // Else j-47; // Increase it with the byte as digit // + 1 to cover for the length part in ILD return i;} // Return the modified input as result  • int c(int i){char[]c=(i+"").toCharArray();int x=i,l=c.length,s=i+l,j=-1;for(;++j<l;x=1)s+=x>0?c[j]-38:38-c[++j];return s;} – Leaky Nun Jun 30 '16 at 9:47 • int c(int i){char[]c=(i+"").toCharArray();for(int x=i,j=-1;++j<c.length;i+=1+Integer.parseInt(x<0?"-"+--c[j+=x=1]:c[j]+""));return i;} it finally felt like golfing in Java @LeakyNun does your variant work? it gives wrong answers at first and then crashes. – cliffroot Jun 30 '16 at 10:07 • @LeakyNun Your code fails at the test case for 0. – Kevin Cruijssen Jun 30 '16 at 10:08 • Oh, how ridiculous; change the two occurrences of 38 to 48. – Leaky Nun Jun 30 '16 at 10:46 • int c(int i){byte[]c=(i+"").getBytes();for(int j=-1;++j<c.length;i+=(c[j]<48?50-c[++j]:c[j]-47));return i;} yay – cliffroot Jun 30 '16 at 11:32 # Perl 6 - 30 bytes As literal as it gets {$^a+$^a.chars+[+]($^a.comb)}


Use it as an anonymous function

> {$^a+$^a.chars+[+]($^a.comb)}(99) 119  ## JavaScript (ES6), 38 bytes n=>eval([n+=,n.length,...n].join+)  Uses the old join-and-eval trick. Save 4 bytes if I can insist on string input: f= n=>eval([n,n.length,...n].join+) ; <input type=number oninput=o.value=f(this.value)><input id=o readonly> • "Add 4 bytes if I have to allow both integers and strings representing integers" You don't, it is optional to choose either, but probably 99.9% will choose integer. I mainly added it for the rare languages that only support strings, but I will remove that part from my question since almost every language does. – Kevin Cruijssen Jun 30 '16 at 12:43 • @KevinCruijssen Sorry for being unclear earlier; the 34-byte version only works on strings. – Neil Jun 30 '16 at 13:33 C++, 255 Bytes #include <iostream> #include <string> #include <stdlib.h> using namespace std; int main(){ string input; cin >> input; int sum = atoi(input.c_str()) + input.length(); for(unsigned i = 0; i < input.length(); ++i) sum += input.at(i) - 48; return 0; }  ## Perl 5 - 37 Bytes warn eval(join'+',/./g)+($_+=()=/./g)


### Usage

echo -n 99 | perl -paF -e'$"="+";$_+=@F+eval"@F"'
119


## Perl, 27 bytes

22 bytes code + 5 for -paF.

Alternative solution, that's a lot more readable for no more bytes. I prefer the other as it looks more cryptic!

$_+=@F+eval join"+",@F  ## dc, 56 bytes ?dZrdd1sa[1+r0r-_1sa]sb0>b[A~rd0<x]dsxxrla*[+z1<y]dsyxp  No shorter than Joe's above, but a somewhat different implementation (and one that takes negative numbers as input vs. a subtraction command). Can probably be golfed more, but lunch only lasts so long. ? #input dZrdd #find no. of digits, rotate to bottom of stack, dup input twice 1sa #coefficient for first digit stored in register 'a' [1+r0r-_1sa]sb #macro 'b' executes on negative numbers. add one (for the neg. sign) #rotate this value out of the way, leave a positive copy on top 0>b #run the above macro if negative [A~rd0<x]dsxx #create and run macro 'x'; mod 10 to grab least significant digit #keep doing it if quotient is greater than zero rla* #a zero remains in the way of our most significant digit, rotate it down #and multiply said digit by our coefficient 'a' from earlier [+z1<y]dsyx #add two top stack values (we left that zero there to ensure this always #works), check stack depth and keep doing it while there's stack p #print!  ## R, 108 bytes A bit late to the party again but here it goes: s=strsplit(paste(n<-scan()),"")[[1]];n+nchar(n)+sum(as.integer(if(n<0)c(paste0(s[1],s[2]),s[1:2*-1])else s))  In order to generally split the digits of any number (e.g. to sum them), R requires us to first convert to a string and subsequently split the string into a string vector. To sum up the elements, the string vector has to be converted to numeric or integer. This together with the exception with the sum of a the digits of a negative number eats up a lot of bytes. The exception can be golfed a bit (to 96 bytes) if warning messages are allowed. s=as.integer(strsplit(paste(n<-scan()),"")[[1]]);if(n<0){s[2]=s[2]*-1;s=s[-1]};n+nchar(n)+sum(s)  In this case the string vector is converted to integer directly using as.integer. However, for negative numbers the first element in the vector will be a minus sign: "-". This causes some trouble, e.g.: as.numeric(c("-",1,2,3)) will return NA 1 2 3 and a warning message. To circumvent this, remove the NA and then multiply the first element with -1 before taking the sum. # RProgN, 30 Bytes ] '' . ] '-?.' | sum _ \ L + +  ## Explination ] # Clone the input # '' . ] # Convert it to a string, then clone it again. '-?.' | sum # Split it into chunks via the pattern '-?.' (A - if there is one, followed by a single character). Sum the resulting array. _ # Floor the value, purely because I hate floats. \ L + + # Swap the top value with the value underneith it, to work with the string again. Get it's length, add the top, middle, and bottom, which is now the length, the sum and the input respectively.  Try it Online! # Perl 5, 22 + 1 (-p) = 23 bytes $_+=eval s//+/gr.y///c


Try it online!

# AWK, 64 63 61 bytes

{s=j=0;for(;j++<n=split($1,a,"");s+=$1>0||j-2?a[j]:-a[j]);$0+=n+s}1  Try it online! TIO link has 6 extra bytes s=j=0; to allow for multi-line input. This is the shortest method I could come up with. I'm curious if it can be done shorter in AWK. Saved 2-bytes, thanks Kevin • Can't $0=n+s+$0 be golfed to $0+=n+s` (-2 bytes)? – Kevin Cruijssen Feb 16 '18 at 17:26
• You are absolutely right @KevinCruijssen . Silly me. – Robert Benson Feb 18 '18 at 3:22