Comments on How many odd digits?
Parent
How many odd digits?
Given a positive integer, count its odd digits.
Input
- An integer from 1 to 999,999,999, inclusive, in any of the following formats:
- A number (such as an integer or floating point number), like
123
. - A string, like
"123"
. - A sequence of characters (such as an array or list), like
['1', '2', '3']
. - A sequence of single digit numbers, like
[1, 2, 3]
.
- A number (such as an integer or floating point number), like
Output
- The number of odd digits in the input.
Test cases
Test cases are in the format input : output
.
1 : 1
2 : 0
3 : 1
4 : 0
5 : 1
6 : 0
7 : 1
8 : 0
9 : 1
10 : 1
11 : 2
12 : 1
13 : 2
14 : 1
15 : 2
16 : 1
17 : 2
18 : 1
19 : 2
20 : 0
111111111 : 9
222222222 : 0
123456789 : 5
999999999 : 9
Scoring
This is a code golf challenge. Your score is the number of bytes in your code. Lowest score for each language wins.
Explanations are optional, but I'm more likely to upvote answers that have one.
[C (gcc)], 37 bytes This ta …
2mo ago
[C (gcc)], 41 bytes …
2mo ago
Vyxal, 4 bytes Expects a stri …
2mo ago
JavaScript, 25 bytes Input …
3mo ago
Japt `-mx`, 2 1 byte u …
2mo ago
Python, 37 27 bytes First, …
3mo ago
Post
Python, 37 27 bytes
First, with input as an integer:
lambda i:sum(ord(x)&1for x in str(i))
This converts the number to string (in the base-10 default) and processes each character. It exploits the fact that digit symbols 0
..9
are consecutive in Unicode and 0
corresponds to an even code point (if it were odd, the code would have to use ord(~x)
instead).
ord
is used to process each character individually. The alternative would be to convert the string to bytes and use the numeric values that come (assuming Python 3.x) from iterating over the bytes
directly. However, any such conversion results in longer code. Also, while Python offers direct int->bytes conversions, they do the wrong thing: bytes(i)
creates an object of that many bytes with all zero values, and i.to_bytes()
gives a binary representation.
As a list of digit values, of course we can just process them directly:
lambda i:sum(x&1for x in i)
This can be done in pure FP primitives instead of using a comprehension. But it's longer, despite the eta reduction:
lambda i:sum(map((1).__and__,i))
(The parentheses around 1
are syntactically necessary.)
1 comment thread