Challenge
- Given a non-negative integer, find the sum of its decimal 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 10100.
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 | output |
|---|---|
123 |
6 |
888 |
24 |
1024 |
7 |
3141592653589793238462643383279502884197169399375105820974944592 |
315 |
Scoring
- This is a code‐golf challenge, so the shortest code (in bytes) wins.
-
4\$\begingroup\$ I have a feeling this is a duplicate... \$\endgroup\$Seggan– Seggan2023年02月24日 23:04:39 +00:00Commented Feb 24, 2023 at 23:04
-
3\$\begingroup\$ this is OEIS A007953 \$\endgroup\$c--– c--2023年02月24日 23:24:00 +00:00Commented Feb 24, 2023 at 23:24
-
\$\begingroup\$ Can I take it as an array with 1 element in it? \$\endgroup\$Kip the Malamute– Kip the Malamute2023年02月25日 00:05:02 +00:00Commented 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– Surb2023年02月26日 20:40:50 +00:00Commented Feb 26, 2023 at 20:40
-
3\$\begingroup\$ @Surb 1 2 3 4 5 6 7 ... there's plenty more \$\endgroup\$naffetS– naffetS2023年03月09日 01:33:48 +00:00Commented Mar 9, 2023 at 1:33
80 Answers 80
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.
-
\$\begingroup\$ And if anyone wants to make a tool like HexagonyColorer so I can make the diagrams look nice instead of hand-drawing them in paint, that'd be appreciated. If not I'll just keep doing them in paint, I don't honestly care enough to make a tool of my own. \$\endgroup\$Bbrk24– Bbrk242023年02月24日 23:48:46 +00:00Commented Feb 24, 2023 at 23:48
Vyxal s, 0 bytes
That's right. No bytes needed.
Alternatively
Vyxal, 1 byte
∑
Just the built-in that works on numbers
-
\$\begingroup\$ 0 bytes is a really cool one and quite rare! \$\endgroup\$Surb– Surb2023年02月26日 20:38:39 +00:00Commented Feb 26, 2023 at 20:38
-
\$\begingroup\$ Make an answer that also optimises your hard drive to save memory \$\endgroup\$The Empty String Photographer– The Empty String Photographer2023年05月19日 11:40:22 +00:00Commented May 19, 2023 at 11:40
-
\$\begingroup\$ @AitzazImtiaz FYI, it's discouraged to accept answers on CGCC. Answers aren't all competing with each other, they're competing within languages, so there's no one winner per se. An accepted answer might also discourage more answers to your question. I'd suggest unaccepting this answer. \$\endgroup\$user– user2023年08月04日 19:36:07 +00:00Commented Aug 4, 2023 at 19:36
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! :-)
-
\$\begingroup\$ Yes, you're right about the stdin/stout requirement, as the challenge author explicitly allowed in the question comments "function declaration" (which I and most interpreted as standard I/O rules) \$\endgroup\$qwr– qwr2023年02月26日 18:34:52 +00:00Commented Feb 26, 2023 at 18:34
-
\$\begingroup\$ I don't think empty string needs to be handled based on the challenge requirement: "given a non-negative integer", which an empty string isn't. Also a fully custom calling convention isn't cheating at all, per the x86 golfing tips page. \$\endgroup\$qwr– qwr2023年02月26日 18:54:07 +00:00Commented Feb 26, 2023 at 18:54
-
\$\begingroup\$ By the way, how did you get such a nice code listing? I generate a NASM listing and manually remove spacing. \$\endgroup\$qwr– qwr2024年09月08日 01:44:03 +00:00Commented Sep 8, 2024 at 1:44
-
\$\begingroup\$ @qwr I actually don't remember exactly what I did, but I probably used this online assembler/disassembler, with some manual fix-up, like always capitalizing hex digits and adding the comments. \$\endgroup\$Cody Gray– Cody Gray2024年09月08日 10:12:55 +00:00Commented Sep 8, 2024 at 10:12
-
\$\begingroup\$ Ah okay. It's probably doable with some vim trickery or command line tools since nasm appears to always use the same width output. Maybe I'll ask a separate question on SO about it. \$\endgroup\$qwr– qwr2024年09月08日 15:48:12 +00:00Commented Sep 8, 2024 at 15:48
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.
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
-
2\$\begingroup\$ I think there's nothing wrong with taking the input as a string, which would save you 3 bytes and allow to support the last test case. \$\endgroup\$Arnauld– Arnauld2023年02月26日 10:26:25 +00:00Commented Feb 26, 2023 at 10:26
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
-
2\$\begingroup\$ 2 bytes alternative:
1ö(useful if you want to sum the digits of numbers within a list, since1öis 1 byte less than€SO). :) For this challenge it's just an alternative though. 🤷 \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2023年02月26日 18:36:21 +00:00Commented Feb 26, 2023 at 18:36
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)).
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.
-
\$\begingroup\$ You might save a byte by summing only up to row 99. The rules only require accepting input up to 10^100, not explicitly including 10^100. \$\endgroup\$user117069– user1170692023年02月26日 12:29:09 +00:00Commented Feb 26, 2023 at 12:29
-
\$\begingroup\$ Ah, ok. I've always interpreted "up to" as "up to and including" when not told otherwise, though your interpretation does make more sense. Thanks a lot, will amend. \$\endgroup\$Jos Woolley– Jos Woolley2023年02月26日 12:48:06 +00:00Commented Feb 26, 2023 at 12:48
-
1\$\begingroup\$ You can save another byte with
ROW(A:A). \$\endgroup\$Engineer Toast– Engineer Toast2023年02月27日 12:27:47 +00:00Commented Feb 27, 2023 at 12:27 -
\$\begingroup\$ @EngineerToast Ah, of course! I'd never use that in a real situation due to the inefficiency, but here every byte counts, thanks! \$\endgroup\$Jos Woolley– Jos Woolley2023年02月27日 14:37:40 +00:00Commented Feb 27, 2023 at 14:37
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
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
-
1\$\begingroup\$ Your first two answers should be able to drop the
/1if I'm not mistaken. \$\endgroup\$Giuseppe– Giuseppe2023年02月26日 13:10:24 +00:00Commented Feb 26, 2023 at 13:10 -
\$\begingroup\$ @Giuseppe yeah, had a brainfart \$\endgroup\$badatgolf– badatgolf2023年02月26日 14:12:33 +00:00Commented Feb 26, 2023 at 14:12
-
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
-
\$\begingroup\$ This appears to be 18 bytes, not 16. I think you may have forgotten to count the initial
xorinstruction outside of the loop? Also, fun fact, this is almost exactly the machine code that GCC will generate for the "obvious" C code when optimizing for size (-Os): Godbolt demo (it swaps the order of thecmpandlea; the advantage of that is unclear, but at least it's not harmful, since thecmpwith a memory operand isn't going to be able to macro-fuse with thejneanyway). \$\endgroup\$Cody Gray– Cody Gray2023年02月26日 13:58:24 +00:00Commented Feb 26, 2023 at 13:58 -
\$\begingroup\$ @CodyGray you're right about counting the xor. I think I got confused with a program starting at _start being initialized with zeros in most registers codegolf.stackexchange.com/questions/132981/… \$\endgroup\$qwr– qwr2023年02月26日 18:44:05 +00:00Commented Feb 26, 2023 at 18:44
-
\$\begingroup\$ The comment indexing with
iis also misleading too. I started with assembly-like C and cheated by seeing what the compiler generated which is why they're so similar \$\endgroup\$qwr– qwr2023年02月26日 18:46:36 +00:00Commented Feb 26, 2023 at 18:46 -
\$\begingroup\$ This might be a noob question, but how exactly the input value is imported to ESI? \$\endgroup\$Glory2Ukraine– Glory2Ukraine2024年09月08日 06:31:45 +00:00Commented Sep 8, 2024 at 6:31
-
1\$\begingroup\$ @int21h That is part of the calling convention. The answer is defining a
sum_digitsfunction callable from C with the System V AMD64 ABI (commonly used for x86-64 processors on Linux and other operating systems). That calling convention says that the second integer argument to a function will be passed in theESIregister. In short, getting the input value intoESIis the caller's responsibility, which a C compiler like GCC will do, and thus it's part of the higher-level calling code, not part of this entry. \$\endgroup\$Cody Gray– Cody Gray2024年09月08日 10:18:17 +00:00Commented Sep 8, 2024 at 10:18
-
\$\begingroup\$ What's with the logarithm? Did the scoring change? \$\endgroup\$Mark Reed– Mark Reed2023年03月03日 02:58:47 +00:00Commented Mar 3, 2023 at 2:58
-
\$\begingroup\$ @MarkReed Fig uses an irrational byte scoring system, which is allowed \$\endgroup\$Seggan– Seggan2023年03月03日 16:15:31 +00:00Commented Mar 3, 2023 at 16:15
-
\$\begingroup\$ @Seggan : yeah who says it's allowed to use a TRANSCENDENTAL scoring system ? \$\endgroup\$RARE Kpop Manifesto– RARE Kpop Manifesto2025年03月26日 12:09:34 +00:00Commented Mar 26 at 12:09
-
\$\begingroup\$ @RAREKpopManifesto it's theoretically possible to build such a computer. For example a trinary computer would use a logarithmic amount of bits. So long as it's theoretically physically possible, it's allowed by the rules of the site \$\endgroup\$Seggan– Seggan2025年03月26日 16:55:49 +00:00Commented Mar 26 at 16:55
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.
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
-
1\$\begingroup\$ you forgot to update the playground link and golfed snippet \$\endgroup\$ASCII-only– ASCII-only2023年02月27日 06:03:55 +00:00Commented Feb 27, 2023 at 6:03
-
\$\begingroup\$ @ASCII-only fixed, thanks \$\endgroup\$noodle person– noodle person2023年02月27日 11:12:46 +00:00Commented Feb 27, 2023 at 11:12
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
-
1\$\begingroup\$ You can remove
s=\$\endgroup\$MarcMush– MarcMush2023年03月05日 19:22:57 +00:00Commented Mar 5, 2023 at 19:22
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
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...
-
\$\begingroup\$ IMO the output of
2for the input3141592653589793238462643383279502884197169399375105820974944592is slightly more than a simple "floating point error" :P \$\endgroup\$Kaddath– Kaddath2023年02月27日 11:13:02 +00:00Commented Feb 27, 2023 at 11:13 -
\$\begingroup\$ @Kaddath that is floating point errors. The input number is too large. A difference of 300 is much smaller compared with the input number. \$\endgroup\$tsh– tsh2023年02月27日 12:34:53 +00:00Commented Feb 27, 2023 at 12:34
-
\$\begingroup\$ Yes I was just joking, my attempt with PHP gave 78, it depends on your max int value I guess, anyway most answers just ignored the 10^100 integer rule and take the input as a string \$\endgroup\$Kaddath– Kaddath2023年02月27日 14:35:42 +00:00Commented Feb 27, 2023 at 14:35
-
\$\begingroup\$ This is the most beautiful thing I have ready today. Thank you! \$\endgroup\$PuercoPop– PuercoPop2023年04月05日 03:18:51 +00:00Commented Apr 5, 2023 at 3:18
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
-
\$\begingroup\$ You don't need
splitin Raku anyway; just useget.comb. \$\endgroup\$Mark Reed– Mark Reed2023年03月03日 03:00:29 +00:00Commented Mar 3, 2023 at 3:00 -
\$\begingroup\$ @MarkReed Thanks, edited to add that. I saw
.combs documentation, but I didn't notice there was a nullary version. \$\endgroup\$MCLooyverse– MCLooyverse2023年03月03日 16:10:19 +00:00Commented Mar 3, 2023 at 16:10 -
\$\begingroup\$ Welcome to Code Golf, and nice first answer! \$\endgroup\$The Thonnu– The Thonnu2023年03月10日 20:00:08 +00:00Commented Mar 10, 2023 at 20:00
-
\$\begingroup\$ Fun tips,
.sumis the same size as[+], so this could beget.comb.sum.sayfor the same amount of bytes, or*.comb.sum.sayin function form \$\endgroup\$Jo King– Jo King2023年05月18日 00:38:39 +00:00Commented May 18, 2023 at 0:38
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
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
APL, 5 bytes
+/⍎ ̈⍞
Explanation:
⍞reads standard input as a character vector⍎ ̈converts each digit to its numeric value+/computes the sum
-
1\$\begingroup\$ You need
⍞instead of⍕. Try it online! \$\endgroup\$Adám– Adám2023年04月05日 06:25:08 +00:00Commented Apr 5, 2023 at 6:25 -
\$\begingroup\$ I was assuming the usual conventions where "take as input" could be arguments to a function instead of literal I/O. \$\endgroup\$Mark Reed– Mark Reed2023年04月05日 14:48:51 +00:00Commented Apr 5, 2023 at 14:48
-
\$\begingroup\$ It does say Your program should take input from standard input (stdin) and output the result to standard output (stdout). but even if your solution is taken as a function, it'd not work, as it'd be a 3-train, and equivalent to
{(+/⍵)⍎¨(⍕⍵)}and even if taken as a snippet (which isn't allowed per site rules), it'd fail on large numbers due to precision. \$\endgroup\$Adám– Adám2023年04月05日 16:46:07 +00:00Commented Apr 5, 2023 at 16:46
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)
-
\$\begingroup\$ 34 bytes:
a=n=>(x=BigInt(n))&&x%10n+a(x/10n)\$\endgroup\$noodle person– noodle person2023年04月05日 22:02:21 +00:00Commented Apr 5, 2023 at 22:02
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()
-
-
\$\begingroup\$ Here's one using only 34 bytes, but it can feel a bit like cheating. \$\endgroup\$JSorngard– JSorngard2023年04月06日 13:00:22 +00:00Commented Apr 6, 2023 at 13:00
-
\$\begingroup\$ @JSorngard Thanks. I think choosing the correct input and output types is an important part of solving a challenge, especially for Rust. \$\endgroup\$corvus_192– corvus_1922023年04月07日 10:02:39 +00:00Commented Apr 7, 2023 at 10:02
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.