# Sum every second digit in a number

I have a number like this:

n = 548915381


The output should be the sum of every second digit of that number. In this case 26:

4+9+5+8 = 26


Rules:

• This is a , so the shortest code in bytes wins.
• The input consists only of numbers bigger than 10 (at least 2 digits) but smaller than a 32-bit integer.
• The input will be a number, not a string

Test cases:

Input Output
10 0
101011 1
548915381 26
999999 27
2147483647 29
999999999 36
• Can we take input either as a string or a digit array? Commented Dec 18, 2022 at 17:42
• Technically, it should be a number. Take whichever is closer in said programming language Commented Dec 18, 2022 at 18:17
• While we advise against accepting an answer in the first place to [code-golf] challenges, as it gives the impression that the challenge is "over", if you do accept an answer, it's recommended to wait longer than a day, to give everyone enough opportunity to participate. Commented Dec 19, 2022 at 11:04
• The formulation is ambiguous. At first, I thought the first two outputs would be 1 and 3, for example… The chosen order defining "every second digit" isn't "natural" in programming terms. Commented Dec 21, 2022 at 8:08
• A specification shouldn't be inferred from test cases. Since there's only one input for which it's different, I actually assumed it takes digits from right to left until I saw the first answer! Commented Jan 24, 2023 at 17:00

# Vyxal, 2 bytes

y∑


well.

Explanation

y∑
y   Uninterleave, push two lists with every second and every second+1 digit
∑  Sum the first list

• Wouldn’t that by 4 bytes? ∑ takes 3 bytes in UTF-8, 2 bytes in UTF-16 (but then y takes 2 bytes too).
– Lazy
Commented Dec 18, 2022 at 17:11
• @Lazy Vyxal uses a custom (SBCS) character set, which means it has 64 single-byte characters. Commented Dec 18, 2022 at 18:54
• Ah, good to know.
– Lazy
Commented Dec 18, 2022 at 19:03
• Why is the s solution not primary?
– Adám
Commented Dec 24, 2022 at 21:51
• @Adám I kinda want to have a 1-byte answer, but I feel like that's cheating Commented Dec 25, 2022 at 14:18

# R, 4038 36 bytes

Edit: -2 bytes thanks to @Giuseppe.

\(x)sum(x%/%10^(nchar(x):0)%%10*1:0)


Attempt This Online!

• 38 Commented Dec 18, 2022 at 15:43
• @Giuseppe nice one, thanks! Commented Dec 18, 2022 at 19:23

## Python 3, 28 37 32 30 35 bytes

lambda n:sum(map(int,str(n)[1::2]))


Assuming input is a string number

• You might want to include a link, eg. ato Commented Dec 18, 2022 at 14:10

# Raku, 15 bytes

{sum m:g/.<(./}


Try it online!

Simple regex based sum of every other digit

# JavaScript (ES6), 30 bytes

-1 by @l4m2

f=n=>n&&f(i=n/10|0)+i++%2*n%10


Try it online!

# JavaScript (ES6), 31 bytes

f=n=>n?f(n/10|0)+i++%2*n%10:i=0


Try it online!

### 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

• 30
– l4m2
Commented Dec 18, 2022 at 11:45

# Japt-hx, 3 bytes

ì ó


Try it

ì ó     :Implicit input of integer
ì       :Convert to digit array
ó     :Uninterleave
:Implicit output of sum of last element


# ><>, 14 bytes

0i~i:c%@0(?n+!


Try it online!

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


# Perl-p, 18 bytes

s/.(.)/$\+=$1/ge}{


Try it online!

Input via STDIN.

for _ c (fold -1)let t+=c;<<<$t  Attempt This Online! -3 bytes thanks to roblogic Inputs as a string, because there is no way to input as a number in Zsh. • Not bad, I would have done, for j k (${(s::)1})((s+=k));<<<$s for 33 bytes... Commented Dec 19, 2022 at 10:31 # Python 2, 39 32 bytes -7 (pxeger suggested lambda) lambda n:sum(map(int,n[1::2]))  TIO EDIT: new test cases • You can shorten this by using a lambda: lambda n:sum(map(int,n[1::2])) Commented Dec 18, 2022 at 11:27 # Excel, 39 32 bytes =SUM(--(0&MID(A1,2*ROW(A:A),1)))  • You can get it down to 32 bytes by not worrying about how long the string is and handling the blank strings instead: =SUM(--(0&MID(A1,2*ROW(A:A),1))) Commented Dec 19, 2022 at 20:34 • @EngineerToast very cool! – jdt Commented Dec 20, 2022 at 2:07 # Pip, 10 7 bytes $+@SUWa


First pip answer, so don't sue me plz.

Try It Online!

Explanation

$+@SUWa @SUWa Uninterweave a, take the second item of the two "every second element" lists$+       Sum the string


• 9 bytes Commented Dec 18, 2022 at 22:55
• 7 bytes: $+@SUWa Commented Dec 19, 2022 at 1:28 • Why would anyone sue you for being awesome? ;^) @Steffan, that's really clever! A couple alternate 7 byters for completeness: $+@RUWa or $+DQUWa. (Also, $+*SUWa and S$+*UWa technically output as a singleton list, but it looks the same without flags.) Commented Dec 19, 2022 at 5:04 • @Steffan huh wow okaay. So @ can be used to convert a number to a string? Commented Dec 19, 2022 at 12:47 • @Steffan I think you meant to say S returns all but the first item (SUW = S UW). Commented Dec 19, 2022 at 18:22 # Ruby, 4032 31 bytes -8 bytes thanks to G B -1 byte thanks to Armand Fardeau ->n{eval"#{n}".scan(/.(.)/)*?+}  Attempt This Online! • You can get 30 bytes with -n flag: gsub(/.(.)/){$.+=eval$1};p$.-1 Commented Dec 19, 2022 at 1:55
• Shorter version (31 bytes): ->n{eval"#{n}".scan(/.(.)/)*?+} tio.run/##KypNqvz/v0BBw0hPzzDVTFMvN7GgWiHeUEFfwVChpgbCAhK1//… Commented Dec 23, 2022 at 22:39
• @ArmandFardeau Thanks! Commented Dec 27, 2022 at 18:06

# Pyth, 9 bytes

tssM%2+1z


Try it online!

      +1z    # Append '1' before the input
%2       # Every 2nd element of
ssM         # Map to integer and take sum
t            # Decrease by 1


# Jelly, 5 bytes

D0ÐoS


Try it online!

Also 5 bytes

DŻm2S


Try it online!

Also also 5 bytes

Ds2SṪ


Try it online!

### 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

• Isn't D0ÐoS another language invented by Dennis? ;^) Commented Dec 19, 2022 at 5:11

!n=sum(i->i-'0',"$n"[2:2:end])  Try it online! # Factor + math.unicode, 25 bytes [ >dec <odds> 48 v-n Σ ]  Try it online!  ! 548915381 >dec ! "548915381" <odds> ! "4958" 48 ! "4958" 48 v-n ! { 4 9 5 8 } Σ ! 26  # flax, 2 bytes ΣẎ  Try It Online! # J, 15 bytes All credit goes to Raul. [:+/_2}.\,.&.":  Attempt This Online! [:+/_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.

Attempt This Online!

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

• Pretty sure OP doesn't accept a list of digits as input (codegolf.stackexchange.com/questions/255650/…), so some kind of variant of 10&#.inv would be required to convert to digits beforehand Commented Dec 22, 2022 at 21:57
• 1(#.]*0 1$~#),.&.": adapts your approach to the number input requirement. Commented Dec 22, 2022 at 23:17 • Ah, I see. Appreciate it. Very smart use of &. here @Jonah. Will update. Commented Dec 23, 2022 at 21:00 # 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);


# Python 3, 35 bytes

lambda n:sum(map(int,f'{n}'[1::2]))


Try it online!

# 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.

# Charcoal, 7 bytes

ＩΣΦＳ﹪κ²


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

   Ｓ    Cast the input to string
Φ     Filter characters where
κ  Current index
﹪ ² Is odd
Σ      Take the sum
Ｉ       Cast to string
Implicitly print


# 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


# 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


# sclin, 13 bytes

2/1.: map +/


Try it here!

For testing purposes:

"548915381" ; n>o
2/1.: map +/


## Explanation

Prettified code:

2/ 1.: map +/

• 2/ chunk into pairs
• 1.: map get second element of each pair
• +/ sum

# Fig, $$\3\log_{256}(96)\approx\$$ 2.469 bytes

S]y


Try it online!

Port of Vyxal.

S]y
# Uninterleave
]  # Get last
S   # Sum


# Fig, $$\6\log_{256}(96)\approx\$$ 4.939 bytes

S-n2'0


Try it online!

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


# 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

• 43 bytes if you map with the index: {it.mapIndexed{i,a->i%2*(a.code-48)}.sum()}
– user
Commented Dec 24, 2022 at 20:24

# K (ngn/k), 13 bytes

+/(2!!#:)#10\


Try it online!

• 10\ convert (implicit) input integer to a list of its digits
• (2!!#:)# only keep elements at odd indices (0-indexed)
• +/ calculate (and implicitly return) the sum

# Julia, 28 bytes

f(n)=sum(digits(n)[2:2:end])

• It seems like you can make this a function by adding 5 bytes: Try it online! Commented Dec 24, 2022 at 15:32
• the current f(n)=sum(digits(n)[2:2:end]) solution sums the "every second" digits from the end (right to left). note that the starting index is wrong for even length numbers, for those it should be 1. one possible formula is 1+end%2... Commented Jul 25, 2023 at 15:16