22
\$\begingroup\$

Input:

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.
  • If possible, please add a link with a test for your code.
  • Also, please add an explanation if necessary.

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

\$\endgroup\$
2
  • \$\begingroup\$ 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? \$\endgroup\$
    – Yytsi
    Commented Jun 30, 2016 at 16:36
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Jun 30, 2016 at 17:36

34 Answers 34

13
\$\begingroup\$

Python 2, 39 bytes

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

Test suite

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

\$\endgroup\$
3
  • \$\begingroup\$ 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?) \$\endgroup\$ Commented Jun 30, 2016 at 9:19
  • 2
    \$\begingroup\$ @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. \$\endgroup\$
    – Denker
    Commented Jun 30, 2016 at 9:24
  • 1
    \$\begingroup\$ @KevinCruijssen - + 1 -> - 1. The unary plus operator exists, so - + 1 is essentially the same as -(+(1)). +a is the same as a, for numbers. \$\endgroup\$ Commented Jun 30, 2016 at 9:24
10
\$\begingroup\$

05AB1E, 28 20 18 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

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

Pyth, 11 10 bytes

Thanks to @LeakyNun for a byte!

++vj\+`Ql`

Test suite

Explanation

++vj\+`Ql`QQ  # Q = input, last two implicitly added

  vj\+`Q      # Join the input on '+' and eval it
        l`Q   # Length of the input
           Q  # The input itself
++            # Add those three values to obtain the result
\$\endgroup\$
0
7
\$\begingroup\$

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
]:+     add everything together
\$\endgroup\$
0
7
\$\begingroup\$

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
\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ +1 for using something that totally isn't meant for calculating number and making it work anyway. \$\endgroup\$
    – DJMcMayhem
    Commented Jun 30, 2016 at 18:48
  • \$\begingroup\$ Can't you remove some quotes to make it "invalid but good for codegolf"? \$\endgroup\$ Commented Jul 1, 2016 at 10:20
  • \$\begingroup\$ Surely you don't need space after quotes in name="i" select="..." eg <with-param name="i"select="substring($i,$s+2)"/> ? \$\endgroup\$
    – cat
    Commented Jul 1, 2016 at 14:33
  • \$\begingroup\$ @cat There are only three of those in the entire document, and actually removing the space causes xsltproc to choke. \$\endgroup\$
    – psmay
    Commented Jul 1, 2016 at 14:49
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – cat
    Commented Jul 1, 2016 at 14:52
4
\$\begingroup\$

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
\$\endgroup\$
0
4
\$\begingroup\$

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

\$\endgroup\$
4
\$\begingroup\$

Dyalog APL, 19 17 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

\$\endgroup\$
3
\$\begingroup\$

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)
\$\endgroup\$
2
  • 1
    \$\begingroup\$ sum(t+1)+n is shorter than sum([n numel(t) t]) \$\endgroup\$
    – Luis Mendo
    Commented Jul 1, 2016 at 11:10
  • 1
    \$\begingroup\$ Whoa, I spent a while thinking why this works. Great, thanks! \$\endgroup\$
    – pajonk
    Commented Jul 1, 2016 at 13:13
3
\$\begingroup\$

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 :)

\$\endgroup\$
1
  • \$\begingroup\$ 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~! \$\endgroup\$
    – brhfl
    Commented Sep 20, 2016 at 18:35
3
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ @DigitalTrauma that won't work for negative integers. \$\endgroup\$
    – seshoumara
    Commented Sep 26, 2016 at 6:48
  • \$\begingroup\$ @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. \$\endgroup\$
    – seshoumara
    Commented Sep 26, 2016 at 17:20
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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

SpecBAS - 147 bytes

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.

enter image description here

\$\endgroup\$
2
\$\begingroup\$

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();
    }
\$\endgroup\$
4
  • 2
    \$\begingroup\$ pretty sure you can replace string with var and '-' with 45 \$\endgroup\$
    – ScifiDeath
    Commented Jun 30, 2016 at 22:23
  • \$\begingroup\$ you can do (n)=>{.... for an anonymous lambda \$\endgroup\$
    – cat
    Commented Jul 1, 2016 at 15:27
  • \$\begingroup\$ cat could you elaborate? im trying to figure it out by myself but its not working for me. i never did that \$\endgroup\$ Commented Jul 1, 2016 at 17:48
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 16, 2018 at 15:41
2
\$\begingroup\$

Perl 5, 22 + 1 (-p) = 23 bytes

$_+=eval s//+/gr.y///c

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Java 8, 174 136 122 107 105 93 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
\$\endgroup\$
9
  • 1
    \$\begingroup\$ 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;} \$\endgroup\$
    – Leaky Nun
    Commented Jun 30, 2016 at 9:47
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – cliffroot
    Commented Jun 30, 2016 at 10:07
  • \$\begingroup\$ @LeakyNun Your code fails at the test case for 0. \$\endgroup\$ Commented Jun 30, 2016 at 10:08
  • 1
    \$\begingroup\$ Oh, how ridiculous; change the two occurrences of 38 to 48. \$\endgroup\$
    – Leaky Nun
    Commented Jun 30, 2016 at 10:46
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – cliffroot
    Commented Jun 30, 2016 at 11:32
1
\$\begingroup\$

Thunno 2 s, 7 bytes

Ðls'+jE

Try it online! or verify all test cases

Explanation

Ðls'+jE  '# Implicit input
Ð         # Triplicate input
 l        # Push its length
  s       # Swap to get input
   '+j   '# Join on "+"
      E   # Evaluate as Python
          # Sum the stack
          # Implicit output
\$\endgroup\$
1
\$\begingroup\$

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 
\$\endgroup\$
1
\$\begingroup\$

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>

\$\endgroup\$
2
  • \$\begingroup\$ "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. \$\endgroup\$ Commented Jun 30, 2016 at 12:43
  • \$\begingroup\$ @KevinCruijssen Sorry for being unclear earlier; the 34-byte version only works on strings. \$\endgroup\$
    – Neil
    Commented Jun 30, 2016 at 13:33
1
\$\begingroup\$

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;
}
\$\endgroup\$
1
\$\begingroup\$

Perl 5 - 37 Bytes

warn eval(join'+',/./g)+($_+=()=/./g)

Input is in $_

\$\endgroup\$
1
\$\begingroup\$

Javascript (using external library) (45 bytes)

Using a library I wrote to bring LINQ to Javascript, I was able to write the following:

(i)=>i+(i+"").length+_.From(i+"").Sum(x=>x|0)

enter image description here

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Link to library? \$\endgroup\$
    – jado
    Commented Jul 6, 2016 at 21:29
  • \$\begingroup\$ github.com/mvegh1/Enumerable . No docs yet, sorry \$\endgroup\$ Commented Jul 6, 2016 at 21:34
1
\$\begingroup\$

C, 132 116 113 80

t,c;f(char*v){for(c=atoi(v+=t=*v==45);*v;t=0,++v)c+=t?50-*v-2*c:*v-47;return c;}

Function f() takes the input as a string and returns the result as an integer. Full program version (113 bytes):

t;main(int c,char**v){char*p=v[1];c=atoi(p+=t=*p==45);for(c=t?-c:c;*p;++p,t=0)c+=t?50-*p:*p-47;printf("%d\n",c);}

Requires one argument.

\$\endgroup\$
1
\$\begingroup\$

Perl, 27 bytes

22 bytes code + 5 for -paF.

$"="+";$_+=@F+eval"@F"

Explanation

Uses the -a autosplit option with an empty delimiter (-F) creating an array of the digits passed in. Uses the magic variable $" which controls which char is used to join an array when it's interpolated into a string (we use "+" here) and the fact that a list used in scalar context will return the length of the list (the number of digits).

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
\$\endgroup\$
1
\$\begingroup\$

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!
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.