You are given an integer n perform the following steps:
Convert each digit of n into its lowercase English word (e.g., 4 β "four", 1 β "one").
Concatenate those words in the original digit order to form a string s.
Return the number of distinct characters in s that appear an odd number of times.
Example 1:
Input:n = 41
Output:5
Explanation:
41 β "fourone"
Characters with odd frequencies: 'f', 'u', 'r', 'n', 'e'. Thus, the answer is 5.
Example 2:
Input:n = 20
Output:5
Explanation:
20 β "twozero"
Characters with odd frequencies: 't', 'w', 'z', 'e', 'r'. Thus, the answer is 5.
Constraints:
1 <= n <= 109
Solutions
Solution 1: Simulation + Bit Manipulation
Thinking
Spell each digit of \(n\) in English and count letters that occur an odd number of times. Twenty-six letters fit in a bit mask of parities.
XOR the bit of every letter; the popcount is the number of odd letters. The words need not be concatenated into one string.
We can convert each number into its corresponding English word, then count the frequency of each letter. Since the number of letters is limited, we can use an integer \(\textit{mask}\) to represent the occurrence of each letter. Specifically, we can map each letter to a binary bit of the integer. If a letter appears an odd number of times, the corresponding binary bit is 1; otherwise, it's 0. Finally, we only need to count the number of bits that are 1 in \(\textit{mask}\), which is the answer.
The time complexity is \(O(\log n)\), where \(n\) is the input integer. And the space complexity is \(O(1)\).