| Bytes | Lang | Time | Link |
|---|---|---|---|
| 003 | Japt hx | 221218T131318Z | Shaggy |
| 024 | x86 | 240911T022915Z | qwr |
| 012 | K ngn/k | 221223T214430Z | coltim |
| 057 | Red | 240909T075237Z | Galen Iv |
| 040 | bc | 240909T062947Z | roblogic |
| 025 | Arturo | 230106T162010Z | chunes |
| 006 | Husk | 240908T184542Z | int 21h |
| 104 | Acc!! | 221220T055726Z | DLosc |
| 041 | JavaScript | 230125T171920Z | EzioMerc |
| 012 | Uiua 0.11.0 | 240415T032001Z | Tbw |
| 031 | sed r | 240414T222229Z | guest430 |
| 007 | Pip | 221218T203311Z | math sca |
| nan | Commodore BASIC C64/128 | 230725T132934Z | Shaun Be |
| 001 | Thunno 2 S | 230627T183429Z | The Thon |
| 112 | Racket | 230725T121124Z | Ed The & |
| 029 | Bash +coreutils | 221223T144909Z | roblogic |
| 038 | Kamilalisp | 230628T082946Z | Kamila S |
| 043 | Lua | 230409T220931Z | bluswimm |
| 110 | Java 8 OpenJDK 8 | 230402T105913Z | Fhuvi |
| 008 | vemf | 230402T061024Z | la.evis. |
| 104 | jonesforth | 230402T115307Z | allisonl |
| nan | 230124T201511Z | The Thon | |
| 045 | Nibbles | 230124T190818Z | xigoi |
| 031 | Octave | 221218T180803Z | 97.100.9 |
| 028 | jq R | 230106T143005Z | pmf |
| 015 | J | 221219T211506Z | south |
| 100 | Java 19 | 221227T185035Z | Jeremy |
| 031 | Ruby | 221219T013941Z | Jordan |
| 028 | Julia | 221224T120423Z | skuss |
| 053 | Prolog SWI | 221225T144046Z | naffetS |
| 007 | Pyt | 221225T143015Z | Kip the |
| 166 | Matlab | 221223T041932Z | Felipe_ |
| 051 | Kotlin | 221222T213317Z | Seggan |
| 045 | Python 3 | 221220T113854Z | user1139 |
| 006 | Brachylog | 221219T142700Z | Fatalize |
| 032 | Excel | 221218T174426Z | jdt |
| 032 | Python 2 | 221218T112657Z | W D |
| nan | Fig | 221219T181601Z | Seggan |
| 013 | sclin | 221218T142343Z | Mama Fun |
| 033 | Zsh | 221218T113324Z | pxeger |
| 005 | 05AB1E | 221219T112702Z | The Thon |
| 041 | Python 3 | 221218T125113Z | SectorCo |
| 061 | Desmos | 221219T084350Z | Aiden Ch |
| 002 | flax | 221219T081014Z | zoomlogo |
| 018 | BQN | 221219T052637Z | DLosc |
| 025 | Factor + math.unicode | 221219T021406Z | chunes |
| 018 | Perl p | 221219T005740Z | naffetS |
| 035 | Python 3 | 221218T132536Z | Neel Shu |
| 049 | Haskell | 221218T214841Z | naffetS |
| 030 | Julia 1.0 | 221218T214552Z | MarcMush |
| 036 | R | 221218T144224Z | pajonk |
| 005 | Jelly | 221218T175237Z | caird co |
| 012 | pl – Perl OneLiner Magic Wand | 221218T124350Z | Daniel |
| 007 | Charcoal | 221218T143206Z | Neil |
| 012 | Retina 0.8.2 | 221218T142752Z | Neil |
| 035 | Python 3 | 221218T135155Z | U13-Forw |
| 002 | Vyxal | 221218T135022Z | math sca |
| 077 | Dart 2.18.4 | 221218T131621Z | Alex |
| 009 | Pyth | 221218T123028Z | Manish K |
| 014 | ><> | 221218T121105Z | Emigna |
| 030 | JavaScript ES6 | 221218T113433Z | Arnauld |
| 035 | C gcc | 221218T114759Z | l4m2 |
| 015 | Raku | 221218T113449Z | Jo King |
Japt -hx, 3 bytes
Or 2 bytes with input as a string, or 1 byte with input as a digit array.
ì ó
ì ó :Implicit input of integer
ì :Convert to digit array
ó :Uninterleave
:Implicit output of sum of last element
x86, 24 bytes
Since the question counts the digits left-to-right, this routine pushes digits from right-to-left onto the stack, then accumulates the sum as it pops digits left-to-right. Using the stack is efficient as push/pop are both one byte. Input and output in eax, and all other registers used are clobbered. Input is assumed to be a positive integer less than 2^31 as specified vaguely in the question: "smaller than a 32-bit integer" (as well as test cases).
The code ends up being decently short because div conveniently computes the quotient and remainder in one instruction, and the quotient ends in the accumulator eax, the same register as the (lower half) dividend for the next iteration. The same eax which is zero after all digits are pushed then becomes the sum. The digit counter is naturally ecx, which lets me use the ol' loop to save another byte. Also pleasingly, every instruction ends up being two bytes or less.
sumdig2: ; input n in eax
31 C9 xor ecx, ecx ; i = 0
6A 0A push 10
5F pop edi ; load divisor 10
.pushes:
99 cdq ; zero edx, assuming eax sign bit is 0
F7 F7 div edi ; eax = n / 10, edx = n % 10
52 push edx ; push digit
41 inc ecx ; ++i
85 C0 test eax, eax ; do while (n != 0)
75 F7 jnz .pushes
; eax sum = 0
.pops:
5A pop edx ; pop and discard digit
49 dec ecx ; --i
74 05 jz .done ; break if i == 0
5A pop edx
01 D0 add eax, edx ; sum += popped digit
E2 F7 loop .pops ; --i; loop if i != 0
.done:
C3 ret ; output in eax
It doesn't seem to be shorter to keep track of digit count parity and conditionally add, rather than "unrolling" and having an extra break condition. Even with my idea to reuse edi, starting at a known positive value, and neg (2 bytes) to flip sign, it's still the same byte count.
.pops:
5A pop edx ; pop digit
F7 DF neg edi ; flip sign
78 02 js .nosum
01 D0 add eax, edx ; sum += popped digit
.nosum:
E2 F7 loop .pops ; --i; loop if i != 0
K (ngn/k), 13 12 bytes
+/(=\0&)#10\
10\convert (implicit) input integer to a list of its digits(=\0&)#only keep elements at odd indices (0-indexed); literally, take the minimum of the digits and0(to zero-out every value), then use=\(equals-scan) to generate a bit mask with1s in odd indices and0s in even ones+/calculate (and implicitly return) the sum
bc, 40 bytes
for(i=length(a);i>=0;i-=2)b+=a/10^i%10;b
Based on my similar bc solution, but iterating from left to right.
Husk, 6 bytes
Σ→TC2d
A function that takes in a number and returns the sum of its even digits.
Commented:
# implicit input
d # split the number into its digits 12345 -> [1,2,3,4,5]
C2 # separate into pairs of digits [[1,2],[3,4],[5]]
T # transpose into 2 sublists: [[1,3,5],[2,4]]
→ # drop the first sublist
Σ # sum up everything
Acc!!, 176 146 104 bytes
-30 bytes thanks to an idea from Mukundan314
Another -42 bytes thanks to several innovative tricks from Mukundan314
Count i while N {
_+N%48%10
}
Count d while 1 {
Count i while 10/(_/10^d+1) {
Write _/10^(d-i)%10+48
}
}
Explanation
# Loop while [read next character] is not 0 (EOF)
Count i while N {
# Read another character and add the digit it represents to the running tally
# in the accumulator
# Map characters 48..57 to values 0..9 and character 10 (newline) to 0
_+N%48%10
}
# Figure out how many digits the accumulator value has
Count d while 1 {
# The i loop doesn't run until d is the most significant digit of the accumulator
# value, at which point it outputs all the digits and then throws an error,
# ending the program
# d is the most significant digit when _/10^d is 9 or less
# Normally, we could make that comparison by checking 9/(_/10^d), but that
# causes an error if the accumulator is 0, so we instead check whether _/10^d+1
# is 10 or less
Count i while 10/(_/10^d+1) {
# Output each digit from most significant to least significant
Write _/10^(d-i)%10+48
# When d-i becomes negative, the expression is a float, and Write throws
# an error because Python's chr() doesn't accept a float argument
}
}
JavaScript, 41 bytes
Without recursion:
n=>[...''+n].reduce((s,n,i)=>s+=-i%2&n,0)
Try it:
f=n=>[...''+n].reduce((s,n,i)=>s+=-i%2&n,0)
console.log(f(10)) // 0
console.log(f(101011)) // 1
console.log(f(548915381)) // 26
console.log(f(999999)) // 27
console.log(f(2147483647)) // 29
console.log(f(999999999)) // 36
UPD 42 -> 41
Uiua 0.11.0, 12 bytes SBCS
/+≡⋕▽◿2⇡⧻.°⋕
Takes \$n\$ and returns the sum of every other digit of \$n\$.
Explanation
°⋕ # stringify n
⧻. # length of string
⇡ # range [0 ... length]
◿2 # modulo 2, [0 1 0 1 ...]
▽ # filter string by that
≡⋕ # parse each digit
/+ # sum of digits
sed -r, 31 bytes
s/.(.)?/\1+/g
s/.*/bc<<<$[&0]/e
or equivalantly,
sed -r, 31 bytes
s/.(.)?/\1+/g
s/.*/echo $[&0]/e
Pip, 10 7 bytes
$+@SUWa
First pip answer, so don't sue me plz.
Explanation
$+@SUWa
@SUWa Uninterweave a, take the second item of the two "every second element" lists
$+ Sum the string
Commodore BASIC (C64/128, C16/+4, VIC-20, PET, THEC64 Mini/THEC64/THEVIC20) - 88 BASIC Bytes
0 inputn$:iflen(n$)=0thenend
1 iflen(n$)<2orval(n$)<9then3
2 fori=2tolen(n$)step2:n=n+val(mid$(n$,i,1)):next
3 printn
A quick explanation
- Line zero waits for an input; if there is no input, then the program is ended
- Line one checks if the length of the input is 1 character, or the value is fewer than 9, if so, we branch to line 3
- Line two iterates over the string from the second character, and each second character thereafter until the end of the string. The value of each is added to
n(which will be zero before thefor/nextloop). - Line 3 outputs the total sum on
n
Thunno 2 S, 1 byte
^
Thunno 2, 2 bytes
^S
Explanation
^S # Implicit input -> 548915381
^ # Uninterleave -> [5,8,1,3,1], [4,9,5,8]
S # Sum the list -> [5,8,1,3,1], 26
# Implicit output
Racket, 112 bytes
((λ(l)(for/sum([i(range(length l))]#:when(odd? i))(-(char->integer(list-ref l i))48)))(string->list(~a(read))))
Explanation
Creates an anonymous function that receives user input as a list of characters. It then iterates through the length of the list. If the index is an odd number, we transform the current charater into a digit and add it to the sum.
((lambda (lst)
(for/sum ([index (range (length lst))]
#:when (odd? index))
(- (char->integer (list-ref lst index)) 48)))
(string->list (~a (read))))
The mysterious "89" with no input
If you supply this program with no input, you will notice that the final sum would be 89.
That is because we convert the result of read directly into a string.
(~a (read))
When there is no input, the read function returns #<eof>. Our code converts the #<eof> symbol to a string, "#<eof>". Then it loops through all the characters that have odd indices, giving us a list of '(#\< #\o #\>). After that, the characters are converted into ASCII numbers. Since the ASCII value of "0" is 48, we subtract 48 from the result:
; (x - 48 becomes y)
'((#\< 12)
(#\o 63)
(#\> 14))
The numbers are then summed together to get 89.
Have a wonderful week ahead!
Bash +coreutils, 29 bytes
fold -2|cut -c2|paste -sd+|bc
echo `sed -E s'/(.)([0-9])/\2+/g'`0|bc
for z in `fold -1`;{((t+=i++%2?z:0));};echo $t
Java 8 (OpenJDK 8), 110 112 bytes
-2 bytes thanks to @ceilingcat !
Solution using only a single inline Stream, and using a 2-cell array as the accumulator of the reduce to carry both the sum and the index of the current cell.
This could easily be outgolfed by a more classic Java solution.
n->(n+"").chars().mapToObj(e->new int[]{e-48}).reduce(new int[2],(a,b)->new int[]{a[0]+a[1]%2*b[0],++a[1]})[0]
vemf, 25 8 bytes
-17 bytes thanks to language creator
Well this is a fun one.
ª‼│%2╕º+
try it online - uses 8472 as an example
Explanation
ª‼│%2╕º+
ª ' convert to string
‼ ' repeat each character...
│%2 ' (index mod 2) times
╕º ' convert them back to numbers
+ ' sum
Old answer (25 bytes):
{`l←╢αª♣ó╕=_1·αª╕‼.l,-:48+
Explanation
{`l←╢αª♣ó╕=_1·αª╕‼.l,-:48+
{ ' define function. (closing } optional)
`l← ' make a list:
╢ ' (group next 9 characters)
╕ ' for each element of
♣ ' the domain of
αª ' left argument as string,
ó ' is (-1)^x
=_1 ' equal to -1?
· ' discard the return value
স ' for each character,
‼ ' repeat it
.l ' by the corresponding list entry
, ' concatenate the resulting list
-:48 ' subtract 0x30 from each entry, so 1 maps to 0x01 etc
+ ' sum
jonesforth, 104 bytes
: F DUP UWIDTH 1 AND IF BASE @ / THEN 0 SWAP BEGIN BASE @ /MOD -ROT + SWAP BASE @ / DUP NOT UNTIL DROP ;
Less obfuscated version:
: F
\ make sure we have an even number of digits
DUP UWIDTH
1 AND
IF BASE @ / THEN
0 SWAP
( accumulator value )
BEGIN
\ add the smallest digit to the accumulator
BASE @ /MOD ( acc rem quot )
-ROT + SWAP
\ discard the new smallest digit
BASE @ / ( acc v )
\ loop until the value is 0
DUP NOT
UNTIL
DROP
;
This answer needs UWIDTH, which gforth doesn't have, so I specified jonesforth because it definitely works on jonesforth.
It compiles to 124 bytes, which drops to 116 if you have constants defined for 0 and 1. On a 16 bit forth it would theoretically be half that. Also it has the added bonus of working in any base between 2 and 36.
Thunno, \$ 6 \log_{256}(96) \approx \$ 4.94 bytes
dZlAKS
Explanation:
dZlAKS # Implicit input
d # Cast to digits
Zl # Uninterleave
AK # Get last element
S # Sum this list
# Implicit output
Nibbles, 4.5 bytes
+`%~>>`@~
Explanation
+ Sum of
`%~ select every second element, starting at first, in
>> remove first element of
`@~ base 10 digits of
input
Octave, 31 bytes
@(s)sum(num2str(s)(2:2:end)-48)
This converts the number to a string, sums up the character codes in the string, then subtracts the ASCII code for 0 (48) from each character.
J, 15 bytes
All credit goes to Raul.
[:+/_2}.\,.&.":
[:+/_2}.\,.&.":
,.&.": NB. equivalent to ". ,. ": y, convert to digit list
_2}.\ NB. behead each non-overlapping window of size 2
[:+/ NB. sum the resulting column
My original 19 bytes from 11 bytes
1(#.]*0 1$~#),.&.":
Updated to reflect challenge requirements. Thanks to Jonah for the modifications.
1(#.]*0 1$~#),.&.":
,.&.": NB. same as above
1( ) NB. dyadic hook
# NB. use length of right arg to
0 1$~ NB. reshape 0 1, reuses elements to create alternating 1's
]* NB. multiply by the right arg
#. NB. 1 #. y sums the result
Java 19, 100 bytes
Partial program assuming n is the given number:
var m=0;var s=String.valueOf(n);for(var i=1;i<s.length();i+=2)m+=s.charAt(i)-48;System.out.print(m);
Full program using standard input:
interface A{
static void main(String[]a){
var n=Integer.parseInt(a[0]);
//
var m=0;
var s=String.valueOf(n);
for(var i=1;i<s.length();i+=2)m+=s.charAt(i)-48;
System.out.print(m);
//
}
}
Ruby, 40 32 31 bytes
-8 bytes thanks to G B
-1 byte thanks to Armand Fardeau
->n{eval"#{n}".scan(/.(.)/)*?+}
Julia, 28 bytes
f(n)=sum(digits(n)[2:2:end])
Pyt, 7 bytes
ąĐƩ⇹ƧƩ-
ąĐƩ⇹ƧƩ-
ą implicit input (n); convert n to array of digits
Đ duplicate top of stack
Ʃ sum the digits of n
⇹ swap the top two items on the stack
ƧƩ sum every other digit of n, starting with the first
- subtract; implicit print
Matlab, 166 bytes
n = input('Input : ', 's');
d = str2double(regexp(n,'\d','match')); %convert n to a unidimensional matrix
total = 0; %stores total sum
for i = 2:2:length(d) %traverse the unidimensional matrix [ vector ]
total = total + d(i); %sum of every second n
end
disp(['Output : ', num2str(total)]);
Kotlin, 51 bytes
{it.map{it.code-48}.foldIndexed(0){i,a,c->i%2*c+a}}
No TIO link as it doesn't have an updated version, ATO borks with it for some reason.
{it.map{it.code-48}.foldIndexed(0){i,a,c->i%2*c+a}} // String input
{ } // Lambda expression
it.map{it.code-48} // Subtract 48 from each char, turning the string into a list of digits
.foldIndexed(0){i,a,c-> } // Fold over the list, starting with 0. i is the index, a is accumulator, and c is the digit
i%2*c // Multiply the current digit by the index mod 2. If it is even, it resolves to 1*c, otherwise 0*c
+a // Add to accumulator
Brachylog, 8 6 bytes
ġ₂z₁t+
-2 bytes thanks to @DLosc.
Explanation
ġ₂ Group consecutive digits into sublists of 2 elements
z₁ Zip
t Tail
+ Sum
Python 2, 39 32 bytes
-7 (pxeger suggested lambda)
lambda n:sum(map(int,`n`[1::2]))
EDIT: new test cases
Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes
S]y
Port of Vyxal.
S]y
# Uninterleave
] # Get last
S # Sum
Fig, \$6\log_{256}(96)\approx\$ 4.939 bytes
S-n2'0
My original answer before seeing Vyxal.
S-n2'0 # Input as a digit list
n # For every
2 # Second item
' # Replace
0 # With a 0
- # Subtract this from the original list
S # Sum
sclin, 13 bytes
2/`1.: map +/
For testing purposes:
"548915381" ; n>o
2/`1.: map +/
Explanation
Prettified code:
2/` 1.: map +/
2/`chunk into pairs1.: mapget second element of each pair+/sum
Zsh, 33 bytes
for _ c (`fold -1`)let t+=c;<<<$t
-3 bytes thanks to roblogic
Inputs as a string, because there is no way to input as a number in Zsh.
05AB1E, 5 bytes
2ι`SO
Explanation
2ι`SO # Implicit input TOP OF STACK:
2ι # Get every second character ["58131", "4958"]
` # Dump onto the stack "4958"
S # Cast to a list of characters ["4", "9", "5", "8"]
O # Sum it up (implicit cast to integer) 26
Desmos, 61 bytes
D=floor(logk)
f(k)=∑_{n=0}^Dmod(n+D,2)mod(floor(k/10^n),10)
Try It On Desmos! - Prettified
There must be some better way to do this other than separating out the D=floor(logk) lol.
BQN, 18 bytes
1⊑·+˝⌊‿2⥊'0'-˜•Fmt
Anonymous tacit function that takes a number and returns a number. Try it at BQN online!
Explanation
1⊑·+˝⌊‿2⥊'0'-˜•Fmt
•Fmt Format as string
'0'-˜ Subtract '0' character from each, giving a list of digits as numbers
⌊‿2⥊ Reshape into an array with two columns, dropping the last digit if
there is an odd number of digits
·+˝ Sum down each column
1⊑ Take the element at index 1 (0-indexed) in the resulting list
Factor + math.unicode, 25 bytes
[ >dec <odds> 48 v-n Σ ]
! 548915381
>dec ! "548915381"
<odds> ! "4958"
48 ! "4958" 48
v-n ! { 4 9 5 8 }
Σ ! 26
Python 3, 28 37 32 30 35 bytes
lambda n:sum(map(int,str(n)[1::2]))
Assuming input is a string number
Jelly, 5 bytes
D0ÐoS
Also 5 bytes
DŻm2S
Also also 5 bytes
Ds2SṪ
How they work
D0ÐoS - Main link. Takes an integer on the left
D - Digits
Ðo - To digits in odd positions:
0 - Set them to 0
S - Sum
DŻm2S - Main link. Takes an integer on the left
D - Digits
Ż - Prepend a zero
m2 - Take every second element
S - Sum
Ds2SṪ - Main link. Takes an integer on the left
D - Digits
s2 - Slice into pairs
S - Sums
Ṫ - Tail
pl – Perl One-Liner Magic Wand, 12 bytes
Use -o to loop over command line arguments. Global matching regexp returns every other character, in this case digit. By default List::Util::sum is imported, e(cho) its result. On the blog, hover the ▶ button, or the blue code box, to see the result:
pl -o 'e sum/.(.)/g' 10 101011 548915381 999999 2147483647 999999999
Charcoal, 7 bytes
IΣΦS﹪κ²
Try it online! Link is to verbose version of code. Explanation:
S Cast the input to string
Φ Filter characters where
κ Current index
﹪ ² Is odd
Σ Take the sum
I Cast to string
Implicitly print
Retina 0.8.2, 12 bytes
.(.?)
$1$*
.
Try it online! Link includes test cases. Takes input as a string because Retina has no integer types. Explanation:
.(.?)
$1$*
Convert alternate digits to unary, dropping the other digits.
.
Take the sum and convert back to decimal.
Vyxal, 2 bytes
y∑
well.
Try it Online! | 1 byte with s
Explanation
y∑
y Uninterleave, push two lists with every second and every second+1 digit
∑ Sum the first list
Dart (2.18.4), 92 77 bytes
f(n,[i=1])=>[for(;i<(n='$n').length;i+=2)int.parse(n[i])].reduce((v,e)=>v+e);
Pyth, 9 bytes
tssM%2+1z
+1z # Append '1' before the input
%2 # Every 2nd element of
ssM # Map to integer and take sum
t # Decrease by 1
><>, 14 bytes
0i~i:c%@0(?n+!
Explanation
0 # init sum as 0
i~ # discard an input
i: # duplicate an input
c%@ # mod the copy by 12 and move down on stack
0(?n # if the other copy was negative, print the sum
+! # else add copy to sum and skip the next instruction
JavaScript (ES6), 30 bytes
-1 by @l4m2
f=n=>n&&f(i=n/10|0)+i++%2*n%10
JavaScript (ES6), 31 bytes
f=n=>n?f(n/10|0)+i++%2*n%10:i=0
Commented
f = n => // f is a recursive function taking the input n
n ? // if n is not equal to 0:
f(n / 10 | 0) + // do a recursive call with floor(n / 10)
// it's important to understand that:
// 1) n is defined in the local scope of f
// 2) i is defined in the global scope
// 3) we're not going to execute the code that
// follows until the recursion stops and i
// has been initialized
i++ % 2 * // take the parity of i (increment it afterwards)
n % 10 // and multiply by the least significant decimal
// digit of n
: // else:
i = 0 // stop the recursion and initialize i to 0


