| Bytes | Lang | Time | Link |
|---|---|---|---|
| 014 | dc | 250802T161036Z | Toby Spe |
| 104 | GNU sed r | 250802T154803Z | Toby Spe |
| 027 | GNU sed + dc | 250802T150111Z | Toby Spe |
| 168 | Bespoke | 250802T083118Z | Josiah W |
| 024 | AWK | 250801T151510Z | xrs |
| 006 | Uiua | 241123T215544Z | ErikDaPa |
| 042 | Clojure | 240909T174141Z | Martin P |
| 014 | x86 Linux assembly | 230225T024926Z | qwr |
| 057 | Setanta | 240908T172428Z | bb94 |
| 008 | Perl 5 MListUtil=sum pF | 240306T011207Z | Xcali |
| 023 | Scala | 230402T024641Z | 138 Aspe |
| 051 | Swift | 230723T232116Z | macOSist |
| 027 | Java | 230727T064601Z | Top Golf |
| 000 | Thunno 2 S | 230611T163728Z | The Thon |
| 021 | Bash & coreutils | 230606T112900Z | roblogic |
| 027 | Shasta v0.0.11 | 230605T144819Z | noodle p |
| 030 | Python 3 | 230517T212803Z | Hunaphu |
| 018 | C# Visual C# Interactive Compiler | 230519T041457Z | Ivan Nee |
| 006 | Befunge98 PyFunge | 230303T024500Z | yeah ok |
| 056 | Rockstar | 230516T114517Z | Shaggy |
| 018 | Perl 5 F E | 230516T205600Z | plentyof |
| 031 | Zsh | 230515T175116Z | roblogic |
| 042 | Python | 230515T161103Z | The Empt |
| 025 | Nibbles | 230515T135516Z | lyxal |
| 095 | LeafLang | 230515T050430Z | Breadlea |
| 025 | C gcc | 230225T095923Z | badatgol |
| 040 | Lua | 230409T214638Z | bluswimm |
| 030 | Rust | 230226T101354Z | corvus_1 |
| 039 | PowerShell | 230406T133859Z | James Fl |
| 031 | Java 8 OpenJDK 8 | 230406T123230Z | Fhuvi |
| 042 | Javascript | 230405T213211Z | Infigon |
| 005 | APL | 230303T032147Z | Mark Ree |
| 011 | KAP | 230405T025303Z | Elias M& |
| 006 | vemf | 230402T043042Z | mí |
| 005 | K ngn/k | 230402T023813Z | naffetS |
| 015 | Trilangle | 230224T234316Z | Bbrk24 |
| 035 | bc | 230311T115706Z | roblogic |
| 044 | Google Sheets | 230311T072907Z | user1111 |
| 015 | KamilaLisp v0.2 | 230310T194704Z | Kamila S |
| 010 | Julia | 230303T100502Z | Jacobus |
| 009 | Vyxal 3.0.0beta.1 | 230224T231735Z | lyxal |
| 002 | Brachylog | 230227T100429Z | Fatalize |
| 114 | Pascal | 230304T151038Z | Kai Burg |
| 016 | Raku | 230227T214110Z | MCLooyve |
| 037 | Groovy | 230303T134700Z | Christop |
| 009 | APL | 230228T030021Z | fat peng |
| nan | I saw this and just had to give it a go with Java. I mean | 230228T081251Z | Haakon L |
| 013 | J | 230227T182930Z | 永劫回帰 |
| 004 | Pyth | 230227T173335Z | CursorCo |
| 011 | GolfScript | 230227T145126Z | emirps |
| 030 | Excel | 230225T073148Z | Jos Wool |
| 087 | Typescript Type System + hotscript | 230225T003306Z | noodle p |
| 022 | JavaScript Node.js | 230227T081221Z | tsh |
| 150 | BrainFlak | 230227T084333Z | RaviRavi |
| 001 | MathGolf | 230226T183917Z | Kevin Cr |
| 019 | Wolfram Language Mathematica | 230226T141006Z | DavidC |
| 031 | PowerShell Core | 230226T163021Z | user3141 |
| 023 | JavaScript Node.js | 230224T233504Z | noodle p |
| nan | 230226T135259Z | Cody Gra | |
| 025 | Hebigo | 230225T191211Z | gilch |
| 030 | C gcc | 230225T140455Z | c-- |
| 003 | Pip | 230225T092245Z | The Thon |
| 002 | Jelly | 230225T092129Z | The Thon |
| 024 | Python | 230225T084238Z | The Thon |
| 003 | Ly | 230225T050158Z | cnamejj |
| 017 | Ruby | 230225T042034Z | Suever |
| 043 | Standard ML | 230225T032217Z | qwr |
| 018 | Factor + math.unicode | 230225T014146Z | chunes |
| 014 | Proton | 230225T012628Z | hyperneu |
| 003 | Charcoal | 230225T005633Z | Neil |
| 006 | Retina 0.8.2 | 230225T005302Z | Neil |
| 019 | Perl 5 p | 230225T001716Z | Kjetil S |
| 015 | Arturo | 230225T000547Z | chunes |
| 003 | MATL | 230224T235403Z | Suever |
| 009 | Pari/GP | 230224T234044Z | c-- |
| 002 | 05AB1E | 230224T233245Z | c-- |
| nan | 230224T233059Z | noodle p | |
| 001 | Japt x | 230224T232248Z | noodle p |
| nan | Fig | 230224T230518Z | Seggan |
| 000 | Vyxal s | 230224T230306Z | lyxal |
dc, 14 bytes
[A~rd0<x+]dsxx
How it works
The recursive function x divides by 10 (A~) and swaps the results (r) so that the quotient is on top of the stack. The recursion continues until there's nothing left to divide (d0<x), at which point we have a stack made of the digits of the input. We then sum the values (+) as each level of recursion returns.
GNU sed -r, 104 bytes
Works with version 4.2 but not with 4.9 (which doesn't support empty labels, nor backrefs in search strings):
s/0//g
:
s/[2-9]/1&/g
y/123456789/x12345678/
t
:a
s/x/<<123456789x01>/
s/(.)<.*\1(x?.).*>/\2/
ta
s/^$/0/
How it works
# Convert each digit to unary
s/0//g
:u
s/[2-9]/1&/g
y/123456789/x12345678/
tu
# Add 'em all up - see https://codegolf.stackexchange.com/a/235144/39490
:a
s/x/<<123456789x01>/
s/(.)<.*\1(x?.).*>/\2/
ta
# Special-case zero
s/^$/0/
GNU sed + dc, 27 bytes
s/./&+/g
s/.*/dc -e'0 &p'/e
Creates a simple dc program of the form 0 ₁+₂+₃+...+p (where ₁₂₃... are the input digits) and executes it.
Bespoke, 168 bytes
now,in this summation decimal numbers(ASCII)go to some full sum
we can subtract"zero"for an easy handling
starting value is higher(actually nonzero)because EOF equals-I
Input is a series of digit characters. (I tried a version that takes input as a number and does math to it, but it turned out to be 197 bytes.)
Clojure, 42 bytes
#(apply +(map parse-long(map str(str %))))
x86 Linux assembly, 18 15 14 bytes
Custom calling convention because I remembered lodsb exists. Takes input as a null-terminated string in esi, because that's the only way to handle numbers with 100 digits. It turns out the answer is nearly identical to Cody Gray's now, except he cleverly used ah instead of 0 in cmp. Oh well. lea is 4 bytes, the same as sub al,'0'/add edx,eax.
I copied his listing format too because it's nicer to look at than an objdump.
-1 byte from using cdq instead of xor.
sum_digits: ; input: null-terminated string in esi
31 C0 xor eax, eax ; clear upper bits of eax
99 cdq ; zero edx (sum)
.L: ; do
AC lodsb ; al c = *str++
8D 54 02 D0 lea edx, [edx-48+eax] ; sum += c - '0'
80 3E 00 cmp BYTE [esi], 0 ; while (*str)
75 F6 jne .L
C3 ret ; return in edx
Setanta, 57 bytes
gniomh(n){s:=0le i idir(0,fad@n)s+=go_uimh(n[i])toradh s}
Version for native number type (up to \$2^{53}\$), 35 bytes
gniomh f(n){toradh n&n%10+f(n//10)}
Swift, 51 bytes
let s={String($0+0).reduce(0){Int("\($1)")!+$0}}
Java, 27 bytes
for(s=0;n>0;s+=n%10,n/=10);
Input as Integer (n)
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.
Befunge-98 (PyFunge), 9 7 6 bytes
~c%+#q
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@.
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).
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
Nibbles, 2.5 bytes
+`@10
Explained
+`@10
+ # Sum of
`@ # input converted to
10 # base 10 (basically, list of digits)
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.
C (gcc), 29 27 25 bytes
f(i){i=i?i%10+f(i/10):0;}
-2 bytes thanks to Giuseppe
-2 bytes thanks to c--
Takes input as int.
C's int isn't large enough for the last test case.
The bracket around the ternary is truly awful. Wish I could remove that. Thanks c-- again.
C (gcc), 38 36 bytes (no recursion).
a;f(i){for(a=0;i;i/=10)a+=i%10;a=a;}
-2 bytes thanks to Giuseppe
Takes input as int.
C's int isn't large enough for the last test case.
C (gcc), 56 bytes (no recursion) (outgolfed by c-- using recursion).
a,n;f(char*s){for(a=0,n=strlen(s);n--;++s)a+=*s-48;a=a;}
Takes input as string
Rust, 54 47 30 bytes
|n|n.map(|b|b as u64-48).sum()
A function that takes a std::str::Bytes and returns a u64. For the purpose of this challenge, I consider std::str::Bytes to be an iterator of ASCII-characters, which meets our general criteria for a string.
Previous versions:
|mut n|{let mut s=0;while n>0{s+=n%10;n/=10;}s}
|n|n.to_string().bytes().map(|d|u64::from(d)-48).sum()
Javascript, 42 bytes
This new and improved version supports BigInt, as well as numbers and strings. It uses tsh's idea, but it first changes the type and uses the ES10 BigInt. (It also happens to be the shortest I could come up with!)
a=n=>eval("x=BigInt(n);x&&x%10n+a(x/10n)")
I also tried playing around and created these functions:
// BigInt/String/Number
b=n=>eval("l=0;(n+[]).split('').forEach(t=>l+=+t);l")
// String only
c=n=>eval("l=0;n.split('').forEach(t=>l+=+t);l")
// BigInt only
d=n=>n&&n%10n+d(n/10n)
// String/Number
e=n=>+n&&+n%10+e(+n/10|0)
APL, 5 bytes
+/⍎¨⍞
Explanation:
⍞reads standard input as a character vector⍎¨converts each digit to its numeric value+/computes the sum
KAP, 7 characters, 11 bytes:
+/@0-⍨⍕
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.
vemf, 6 bytes
ª-:48+
Input is a number literal.
try it online, uses :314159 as example
Explanation
ª ' represent as a codepage string
-:48 ' subtract 48 from each codepoint
' (so the codepoints are all now 0-9)
+ ' sum list
Trilangle, 15 bytes
'0.<"@(+>i(^-<!
Test it on the online interpreter!
Roughly equivalent to this C code:
#include <stdio.h>
int main() {
int total = 0;
int i;
while ((i = getchar()) != EOF) {
total += i - '0';
}
printf("%d\n", total);
}
Control flow is kinda weird so it actually calls getchar() a couple times even after EOF is reached.
Unfolds to this:
'
0 .
< " @
( + > i
( ^ - < !
With code paths highlighted:
Control flow starts at the north corner heading southwest (on the red path). Instructions are executed as follows:
'0: Push a 0 to the stack<: Change the direction of control flow(Walk off the edge of the grid and wrap around)
i: Get a single character from stdin (-1 on EOF) and push it to the stack>: Branch on the sign of the top of the stack
If the value is positive (any character that isn't EOF), the IP takes the green path:
"0: Push the value of the character '0' (i.e. 48) to the stack-: Subtract the two values on top of the stack+: Add the two values on top of the stack<: Redirect control flow, merging with the red path
Once EOF is read, the IP takes the blue path, printing out the stored value... eventually. As you can see from the image it takes the scenic route.
-: Subtract the two values on top of the stack. There's now only one value,total - -1(i.e.total + 1).i: Attempt to read another character from stdin (always sees EOF)<: Redirect control flow-Subtract the two values on top of the stack. Again, there's now only one value:total + 2.^: Redirect control flow((: Decrement the top of the stack twice, undoing the effects ofi-i-.!: Print the value on top of the stack as a decimal integeri: Another attempt to read stdin, though at this point the values on the stack don't matter@: End program.
bc, 35 bytes
for(;i<length(a);i++)b+=a/10^i%10;b
Using the default scale=0 i.e. no decimals, divide by 1,10,100,... successively (a/10^i), and %10 to add only the last digit to b. When the for loop finishes, print the sum. ;b
Google Sheets, 44 bytes
=QUERY(,"select "®EXREPLACE(A1,"\B","+"))
Julia, 12 10 bytes
Tacit Julia strikes again!
sum∘digits
Explanation:
digits: take an integer and return a vector of its digits in base 10 (default)
∘: function composition
sum: sum a collection
-2 thanks to MarcMush
Vyxal 3.0.0-beta.1, 9 bytes
'%%O48-/+
Try it online! (link is to literate version)
Unlike my v2 answer, there is no sum flag, sum built-in, cast to int or cast to string built in in this version of vyxal (because it's a beta release - what do you expect?).
Explained
'%%O48-/+
'%% ## Format the input as a string
O48- ## get the ordinal value of each character and subtract 48 to get the digit value
/+ ## fold by addition
Brachylog, 2 bytes
ẹ+
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
Pascal, 114 bytes
This is a full program according to ISO standard 7185 “Standard Pascal”.
The built-in data type integer comprises (at least) all integral values in the range −maxInt..maxInt.
The value of maxInt is implementation-defined.
In order to successfully test values up to and including one googol you will need a processor (this refers to the specific combination of machine, compiler, OS, etc.) defining maxInt ≥ 10100.
program p(input,output);var x,y:integer;begin y:=0;read(x);repeat y:=y+x mod 10;x:=x div 10 until x=0;write(y)end.
Ungolfed:
program digitSum(input, output);
var
x, digitSum: integer;
begin
digitSum := 0;
read(x);
repeat
begin
digitSum := digitSum + x mod 10;
x := x div 10;
end
until x = 0;
write(digitSum);
end.
Because in Pascal mod is defined to always yield a non-negative result, digitSum works incorrectly for negative inputs.
Injecting an x := abs(x); prior the loop will resolve this issue.
Another method is of course to process characters.
In Pascal it is guaranteed that the characters '0' through '9' are in ascending order and consecutive, thus ord('9') − ord('0') is guaranteed to yield the integer value 9.
program p(input,output);var x:integer;begin x:=0;while not EOF do begin x:=x+ord(input^)-ord('0');get(input)end;write(x)end.
Input must not be followed by a newline, or replace the EOF by EOLn.
This program is ≥ 124 bytes
Raku, 19 16 bytes
say [+] get.comb
get(): gets a single line from stdin (parens not required)
.comb: splits out to list of characters (thanks
@Mark Reed)
[+]: reduces the list by addition.
say: writes to stdout
APL, 9 bytes (?)
sd←+/⊥⍣¯1
Some characters take probably more than 1 byte, but I am not sure how many...
I saw this and just had to give it a go with Java. I mean, I'm not going to win, but it's in good fun, right? Using loops, assuming that we can have multiple inputs, including 0:
class D{public static void main(String[]a){int s=0;for(String t:a)for(char c:t.toCharArray())s+=c-48;System.out.println(s);}}
That gives 125 bytes, but if we assume some assumptions, we can surely get it lower. If we assume one and only input, we don't have to loop, so we can shorten it down further. But if we also stream, we get:
class D{public static void main(String[]a){System.out.println(a[0].chars().map(i->i-48).sum());}}
Which clocks in at 97 bytes.
That's not too bad for Java.
J, 13 bytes
[: +/ 48 -~ a. I. ]
Pyth, 4 bytes
ssMz
Alternatively there's sjQT or just ssM if we're allowed to have quotes around the input.
GolfScript, 11 bytes
`1/{~}%{+}*
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
Excel, 32 31 30 bytes
=SUM(0+(0&MID(A1,ROW(A:A),1)))
Input in cell A1.
Thanks to user117069 and EngineerToast for the two bytes saved.
Typescript Type System + hotscript, 92 87 bytes
import{Pipe,S,T}from"hotscript"
type _<U>=Pipe<U,[S.Split<"">,T.Map<S.ToNumber>,T.Sum]>
I just found out about this library that basically turns the Typescript Type System into a full-on functional programming language and it's amazing
Saved 5 bytes by taking input as a string instead of a number
import{Pipe,S,T}from"hotscript"
type _<U>= // define hotscript lambda with string argument U
Pipe<U,[ // pipe U to:
S.Split<"">, // split on "" (= character list)
T.Map<S.ToNumber>, // map each letter to number
T.Sum // sum
]> // end pipe
JavaScript (Node.js), 22 bytes
f=n=>n&&n%10+f(n/10|0)
JavaScript (Node.js), 21 bytes
f=n=>n&&n*9%9-f(n/~9)
It is shorter, but with floating point errors...
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
MathGolf, 1 byte
Σ
Explanation:
Σ # Sum the digits of the (implicit) input-integer
# (after which the entire stack is output implicitly as result)
Wolfram Language (Mathematica), 19 bytes
Total@IntegerDigits
Total@IntegerDigits@3141592653589793238462643383279502884197169399375105820974944592
315
PowerShell Core, 31 bytes
%{$s=0;$_|% *ay|%{$s+="$_"};$s}
Input comes from the pipeline
%{$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
JavaScript (Node.js), 23 bytes
n=>eval([...n].join`+`)
Takes input as a string
JavaScript (Node.js), 26 bytes
n=>eval([...""+n].join`+`)
Takes input as a number, doesn't work if the number is too large for JavaScript to stringify naturally
NOTE: Since many/most of the answers seem to ignore the requirement in the question that the input must be taken from
stdinand the output must be sent tostdout, I suppose it is reasonable if I do so, too. I think that's a silly and arbitrary requirement, because it makes many languages non-competitive. The standard on Code Golf is to allow functions, and to allow functions taking input via arguments and outputting via their return value(s), so this is what I will follow.
x86-64 Assembly, standard Linux calling convention, 17 bytes
64 31 C0 0F B6 0F E3 09 48 FF C7 8D 44 01 D0 EB F2 C3
This is a minor, iterative improvement on qwr's answer, which is 18 bytes.
It saves 1 byte by using the relatively-obscure JECXZ instruction (actually JRCXZ, since this is 64-bit mode), which jumps if the value of the rcx register is zero.
It also improves on qwr's original (arguably fixes a bug?) in that it supports the case where the input is an empty string, returning a sum of zero. (To be fair, the challenge doesn't specify whether it is required to handle this, so maybe it cannot be termed a "bug", and, in fact, my next attempt will have this same "bug", so I can hardly ding qwr for taking advantage of it, too!)
SumDigits:
31 C0 xor eax, eax
Loop:
0F B6 0F movzx ecx, BYTE PTR [rdi]
E3 09 jrcxz End
48 FF C7 inc rdi
8D 44 01 D0 lea eax, [rcx + rax - '0']
EB F2 jmp Loop
End:
C3 ret ; result is in eax
x86-64 Assembly, fully custom calling convention, 14 bytes
64 31 C0 31 D2 AC 8D 54 02 D0 38 26 75 F7 C3
This is a variation on the same theme (it still takes the input as a pointer to the beginning of a NUL-terminated ASCII string), but it pulls out all the stops to really optimize for size:
It uses the ultra-compact x86 string instructions. In this case,
lods, which loads a byte intoalfrom the address inrsi, and also incrementsrsito point to the next byte, using a single-byte encoding.- In order to know whether to increment or decrement the source pointer, the
rsiinstruction implicitly depends on the direction flag (DF). Normally, you'd need to explicitly clear that flag with thecldinstruction, but, in this case, since we're running on a *nix-like operating system, per the challenge, we can assume it is already clear. (Also, when you're defining a custom calling convention, the state of the flags can be part of that; see below.)
- In order to know whether to increment or decrement the source pointer, the
It uses a custom calling convention so that we can (A) take the input string in the
rsiregister, which is what thelodsinstruction expects, saving us from having to copy it from one register to another, and (B) build the result in a custom register (edx), freeing upeaxto use as a scratch register (because this is what thelodsinstruction uses as an implicit destination operand).The
lodsinstruction is only loading a single byte, so it only modified the low-order byte of theeaxregister (al). But theleainstruction that we use to perform multiple arithmetic operations in a single instruction only works on the full 64-bit register, so we need to make sure that the high values are clear. We could do this with an explicitmovzxafter thelodsinstruction, but that would consume a lot of bytes. So, instead, we do it once, outside of the loop, with a singlexorinstruction. This clears the entireraxregister, which works because we only ever touch the low-order byte (al).- Another neat trick falls out of this: because we don't touch the high-order byte (
ah), it's guaranteed to be zero through all iterations of our loop, so we can compare (cmp) the source pointer (string) toahinstead of comparing it to a literal 0, which saves us one byte in the encoding.
- Another neat trick falls out of this: because we don't touch the high-order byte (
SumDigits:
-- ; cld ; can assume DF is always clear on Linux)
31 C0 xor eax, eax ; eax = 0 (al = 0, ah = 0)
31 D2 xor edx, edx ; edx = 0 (holds result)
Loop:
AC lods ; al = BYTE PTR [rsi]
8D 54 02 D0 lea edx, [rdx + rax - '0'] ; edx += (eax - '0')
38 26 cmp BYTE PTR [rsi], ah ; is BYTE PTR [rsi] == ah (which is 0)?
75 F7 jne Loop ; loop back if not equal (non-zero)
C3 ret ; result is in edx
The custom calling convention is a pretty major "cheat" here, but it's not unusual in the "real world" to use a custom calling convention when writing code in assembly. If you're going to call it from C, you need to take steps to match the standard C calling convention, but who says we're calling it from C?! We don't need no stinkin' C! :-)
Hebigo, 25 bytes
print:sum:map: int input:
(It compiles to the following Python.)
print(
sum(
map(
int,
input())))
C (gcc), 30 bytes
f(int*s){s=*s?*s-48+f(s+1):0;}
C (clang), 31 bytes
f(*s){return*s?*s-48+f(s+1):0;}
C89, 35 bytes
f(char*s){return*s?*s-48+f(s+1):0;}
Python, 24 bytes
lambda n:sum(map(int,n))
Input as a string.
Python, 29 bytes
lambda n:sum(map(int,str(n)))
Input as an integer.
Ly, 3 bytes
S&+
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.
Ruby, 17 bytes
->x{x.digits.sum}
This defines an anonymous function that accepts a single input (a number), breaks it up into an array of digits, then sums this array and returns the result
Standard ML, 43 bytes
(foldl op+ 0)o map(fn x=>ord x-48)o explode
Lack of sum function strikes again
Factor + math.unicode, 18 bytes
[ >dec 48 v-n Σ ]
>decConvert the input to a string48 v-nSubtract 48 from each code pointΣSum
Proton, 14 bytes
digits(10)+sum
digits(x, y) converts y into digits in base x and sum performs sum. Therefore, digits(10) is a partial function that becomes y => digits(10, y) and + sum chains it with sum so an input will be called with digits(10)(...) first, and then the result is called with sum(...).
This is 6 bytes shorter than the straightforward x=>sum(digits(10,x)).
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
Retina 0.8.2, 6 bytes
.
$*
1
Try it online! Link includes test cases. Explanation:
.
$*
Convert each digit to unary.
1
Convert the sum to decimal.
Arturo, 15 bytes
$=>[∑digits&]
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.
MATL, 3 bytes
!Us
Try it out at MATL Online
Explanation
% Implicitly read in first input, a 1 x N string
! % Flip it so that it is N x 1 character array (one character per row)
U % Convert each row from a string to a number
s % Sum the resulting N x 1 numeric array
% Implicitly display the result
Vyxal s, 0 bytes
That's right. No bytes needed.
Alternatively
Vyxal, 1 byte
∑
Just the built-in that works on numbers
