13
\$\begingroup\$

Challenge

  • Given a non-negative integer, find the sum of its digits.

Rules

  • Your program must take a non-negative integer as input.
  • Your program should output the sum of the digits of the input integer.
  • Your program should be able to handle inputs up to 10^100.

Examples

  • If the input is 123, the output should be 6 (1 + 2 + 3).
  • If the input is 888, the output should be 24 (8 + 8 + 8).
  • If the input is 1024, the output should be 7 (1 + 0 + 2 + 4).
  • If the input is 3141592653589793238462643383279502884197169399375105820974944592, the output should be 315.

Format

  • Your program should take input from standard input (stdin) and output the result to standard output (stdout).
  • Your program should be runnable in a Unix-like environment.

Test cases

Input:

123

Output:

6

Input:

888

Output:

24

Input:

1024

Output:

7

Input:

3141592653589793238462643383279502884197169399375105820974944592

Output:

315

Scoring

  • This is a code-golf challenge, so the shortest code (in bytes) wins.
\$\endgroup\$
7
  • 4
    \$\begingroup\$ I have a feeling this is a duplicate... \$\endgroup\$
    – Seggan
    Commented Feb 24, 2023 at 23:04
  • 3
    \$\begingroup\$ this is OEIS A007953 \$\endgroup\$
    – c--
    Commented Feb 24, 2023 at 23:24
  • \$\begingroup\$ Can I take it as an array with 1 element in it? \$\endgroup\$ Commented Feb 25, 2023 at 0:05
  • 2
    \$\begingroup\$ Congrats on finding a non duplicate challenge which can have an answer of 0 bytes \$\endgroup\$
    – Surb
    Commented Feb 26, 2023 at 20:40
  • 3
    \$\begingroup\$ @Surb 1 2 3 4 5 6 7 ... there's plenty more \$\endgroup\$
    – naffetS
    Commented Mar 9, 2023 at 1:33

72 Answers 72

3
\$\begingroup\$

Leaf-Lang, 95 bytes

macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p 1p s print

Explaination

Leaf Lang is a lang I made in my free time in college. It is a stack-based programming language. It can be hard to understand, so I wrote a step-by-step golf of my solution.

The readable solution

"" input splitString # split input into array of strings
0 : sum              # sum = 0
"" = 0 =             # loop condition
while
        pop pop pop pop      # clean stack of condition
        toNumber sum + : sum # sum = sum + toNumber
        "" = 0 =             # loop condition
stop

pop pop pop pop # clean stack of condition
pop             # clean stack of stop condition

sum # add sum to stack
print

Compressed readable solution, 109 bytes

""input splitString 0:sum""=0=while pop pop pop pop toNumber sum+:sum""=0=stop pop pop pop pop pop sum print

Macro optimization #1, 98 bytes

macro p pop end""input splitString 0:s""=0=while p p p p toNumber s+:s""=0=stop p p p p p s print

This uses a macro to shorten the long chains of pop calls.

Macro optimization #2, 96 bytes

macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p pop s print

The final golf code, 95 bytes

macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p 1p s print

The final code abuses my parser to push a 1 to the stack then call the p macro to essentially make a single pop call.

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

Zsh, 31 bytes

for i (${(s::)1})((n+=i));<<<$n

Try it online!

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

Perl 5 -F -E, 18 bytes

$s+=$_ for@F;say$s

Try it online!

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

Befunge-98 (PyFunge), 9 7 6 bytes

~c%+#q

Try it online!

Having read through the Default I/O thread, it seems my "fun extra" answer is actually valid as a submission. Note that since the output in this version is an exit code, POSIX-compatible systems (including TIO; please let me know if there's a better site for this) will only care about the least significant byte and as such display the result mod 256 (as per the Funge-98 spec).

Explanation

~: Read next character.

c%: Push 12, then take input character mod 12. This gives the number represented. Suggested by Jo King (previous iteration subtracted 48 from the number with '0-).

+: Add that to the current total (initially implicitly 0).

#q: Do nothing if control flow is LTR, quit and return top of stack as exit code if RTL.

Due to wrapping, this is a loop. At EOF, ~ reflects, thus executing the last portion RTL.

Previous version

~'0-+2j@.

Try it online!

Explanation

As above, but replace #q with:

2j@.: Jumps over the exit and print if control flow is LTR, prints top of stack as an integer then exits if RTL (push 2, jump, exit, print).

\$\endgroup\$
1
  • \$\begingroup\$ '0- can be c% \$\endgroup\$
    – Jo King
    Commented May 18, 2023 at 0:41
2
\$\begingroup\$

Japt -x, 1 byte

ì

Try it

ì gets the digits of the number, the -x flag sums the resulting array

\$\endgroup\$
2
  • \$\begingroup\$ Who downvoted this? Can they explain themselves? \$\endgroup\$ Commented Feb 28, 2023 at 0:06
  • 1
    \$\begingroup\$ Well, I am going to upvote it @Jacob cz this is one of the best answer. \$\endgroup\$ Commented Feb 28, 2023 at 16:00
2
\$\begingroup\$

Arturo, 15 bytes

$=>[∑digits&]

Try it

Even though the question says input and output must be via standard IO, the author of the question said functions are allowed in the comments. So this is a function.

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

Charcoal, 3 bytes

IΣN

Try it online! Link is to verbose version of code. Explanation:

  N Input number
 Σ  Sum of digits
I   Cast to string
    Implicitly print
\$\endgroup\$
2
\$\begingroup\$

Standard ML, 43 bytes

(foldl op+ 0)o map(fn x=>ord x-48)o explode

Lack of sum function strikes again

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

Jelly, 2 bytes

DS

Try it online!

D    digits
 S   sum
\$\endgroup\$
2
\$\begingroup\$

Pip, 3 bytes

$+a

Attempt This Online!

$+    sum of
      (the digits of)
  a   the input
\$\endgroup\$
2
\$\begingroup\$

Hebigo, 25 bytes

print:sum:map: int input:

(It compiles to the following Python.)

print(
  sum(
    map(
      int,
      input())))
\$\endgroup\$
2
\$\begingroup\$

PowerShell Core, 31 bytes

%{$s=0;$_|% *ay|%{$s+="$_"};$s}

Input comes from the pipeline

Try it online!

%{$s=0;$_|% *ay|%{$s+="$_"};$s}
%{                            } # % is an alias for the cmdlet ForEach-Object; input (the string containing the number) comes from the pipeline and will be in $_
  $s=0;                         # initialize the final sum
       $_|% *ay                 # takes the input string and passes it to "ForEach-Object -MemberName ToCharArray": turns the string into an array of characters. This is shorter than a cast using [char[]]$_
               |%{$s+="$_"};    # pass the single characters to yet another ForEach-Object which sums up the total. The current character in $_ must be turned into a single-char string by wrapping it in double quotes;
                                # without that, PS would add up the character's byte code since the left operand (the sum) is an integer.
                            $s  # output the sum
\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 19 bytes

Total@IntegerDigits

Try it online!

Total@IntegerDigits@3141592653589793238462643383279502884197169399375105820974944592

315

\$\endgroup\$
1
  • \$\begingroup\$ @The Thonnu, Thanks for the edits, \$\endgroup\$
    – DavidC
    Commented Feb 27, 2023 at 22:03
2
\$\begingroup\$

MathGolf, 1 byte

Σ

Try it online.

Explanation:

Σ  # Sum the digits of the (implicit) input-integer
   # (after which the entire stack is output implicitly as result)
\$\endgroup\$
2
\$\begingroup\$

Brain-Flak, 150 bytes

{(({})<><((()()()()()){})>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}{})<>({}<((()()()()()){})>(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)}<>

Not sure if this counts, because it exceeds TIO's 60s time limit for the 3141592653589793238462643383279502884197169399375105820974944592 test case, as its' time complexity is linear. Theoretically, given enough time, it should output the right answer. This answer is extremely similar in format to my answer here.

{                                                                               #  loop while top of left stack is not 0
(({})<><((()()()()()){})>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}{})<>    #  add the result of modulo 10 of the top value of the left stack to the top value on the right stack
({}<((()()()()()){})>(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)          #  integer division by 10 on left stack
}                                                                               #  end loop
<>                                                                              #  switch to right stack
                                                                                #  implicit output of active (right) stack

Try it online!

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

APL, 9 bytes (?)

sd←+/⊥⍣¯1

Some characters take probably more than 1 byte, but I am not sure how many...

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Golf! Usually for APL, a custom code page is used that makes the characters one byte each. I think Dyalog Extended is the most common one. \$\endgroup\$ Commented Feb 28, 2023 at 3:01
  • \$\begingroup\$ How is this meant to be run? It doesn't read input; it doesn't result in sd being a callable dfn... \$\endgroup\$
    – Mark Reed
    Commented Mar 3, 2023 at 3:06
  • \$\begingroup\$ You don't need to count sd← but you do need to read from stdin in a UNIX environment. While NARS2000 has large integer support, and your algorithm would work there, it doesn't run under UNIX, so you're out of luck. \$\endgroup\$
    – Adám
    Commented Apr 5, 2023 at 6:22
2
\$\begingroup\$

Groovy, 37 bytes

def c={("$it"as List).sum{it as int}}

Try it online!

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

Brachylog, 2 bytes

ẹ+

Try it online!

Explanation

is a pretty disgusting built-in for a declarative logic language, but it’s useful. A "better" alternative would be ∋ᶠ (find all elements) but it’s longer.

ẹ     Split into a list of elements
 +    Sum
\$\endgroup\$
2
\$\begingroup\$

KamilaLisp v0.2, 15 (APL SBCS)

$(⌿.← +)∘:⊙⍫∘⍫∧

Equivalent to $(foldl1 +)@:parse-number@str:explode.

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

KAP, 7 characters, 11 bytes:

+/@0-⍨⍕

Try it online.

It appears that one needs bigint support to properly answer this question. If strings are allowed then the last character can be removed from the answer.

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

Lua, 40 bytes

a=0(...):gsub('.',load'a=...+a')print(a)

Try it online!

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

Nibbles, 2.5 bytes

+`@10

Attempt This Online!

Explained

+`@10
+      # Sum of
 `@    # input converted to
   10  # base 10 (basically, list of digits)
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice. You can save a nibble by using the default (~) value for "to base" (`@), which is 10: try it \$\endgroup\$ Commented Jun 6, 2023 at 12:13
2
\$\begingroup\$

Rockstar, 75 65 56 bytes

listen to N
cut N
X's 0
while N
let X be+roll N-0

say X

Try it here (Code will need to be pasted in)

listen to N     :Read input string into variable N
cut N           :Split to an array
X's 0           :Initialise X as 0
while N         :While N is not empty
let X be+       :  Increment X by
  roll N        :    Pop the first element from N
  -0            :    Subtract an 0 to cast it to an integer
                :End while loop
say X           :Output X
\$\endgroup\$
2
\$\begingroup\$

Shasta v0.0.11, 27 bytes

{(eval(join(split$"")"+"))}

{...} Function of argument $

(eval ...) Evaluate as JavaScript

(join ... "+") Join on "+"

(split $ "") Characters of the input string

Alternative 27 bytes:

{(sum(map(split$"")number)}

The sum of mapping each character of the input string to number.

Online interpreter will be set up very soon; for now, you can test this by following instructions from the README on GitHub.

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

Scala, 23 bytes

Try it online!

x=>x.map(_.asDigit).sum
\$\endgroup\$
1
\$\begingroup\$

Factor + math.unicode, 18 bytes

[ >dec 48 v-n Σ ]

Attempt This Online!

  • >dec Convert the input to a string
  • 48 v-n Subtract 48 from each code point
  • Σ Sum
\$\endgroup\$
1
\$\begingroup\$

Ly, 3 bytes

S&+

Try it online!

Breaks STDIN into digits and pushes onto the stack, then uses &+ to sum them. Prints the stack as a number be default when the code exits.

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

GolfScript, 11 bytes

`1/{~}%{+}*

Try it online!

A function which takes a single integer as input. Link includes test cases.

Explanation

`1/{~}%{+}* # whole function
`           # convert the input into a string
  /         # split into groups of size
 1          # 1
   { }%     # for each value in the split groups...
    ~       # eval it
       {+}* # sum this `eval`ed array
\$\endgroup\$
1
\$\begingroup\$

Pyth, 4 bytes

ssMz

Try it online!

Alternatively there's sjQT or just ssM if we're allowed to have quotes around the input.

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

J, 13 bytes

[: +/ 48 -~ a. I. ]
\$\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.