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 …
1mo ago
[C (gcc)], 41 bytes …
1mo ago
Vyxal, 4 bytes Expects a stri …
2mo ago
JavaScript, 25 bytes Input …
3mo ago
Japt `-mx`, 2 1 byte u …
1mo ago
Python, 37 27 bytes First, …
3mo ago
Post
C (gcc), 41 bytes
r;o(char*s){for(;*s;r+=*s++&1);return r;}
This is under the assumption that in a function solution, input has to be passed as parameter and output through the return value. The result variable is allocated outside the function to get gcc implicit int declaration and zero initialization for free.
It's very straight-forward: input as string, iterate until null terminator found. Mask each character's ASCII value with 1 to see if odd or even, under the assumption that '0'
== 48, an even value. From there, ASCII character are guaranteed to be adjacent in the symbol table.
I also tried to write it with recursion but got exactly the same amount of characters (41):
r;o(char*s){r+=*s&1;*s&&o(s+1);return r;}
Printing the result inside the function also works but is longer:
r=48;o(char*s){for(;*s;r+=*s++&1);puts(&r);}
1 comment thread