Given an integer n
, you need to remove all digits that appear an odd number of times in the integer. For example, given the integer 122334
, the digit 1
appears once (odd), the digit 2
appears twice (even), the digit 3
appears twice (even), and the digit 4
appears once (odd). After removing the digits that appear an odd number of times, the result would be 2233
.
n
(is it positive, negative, any size constraints)?We will write a function clearOddDigits
which handles the given problem. It will first count the occurrences of each digit in the input, and then construct the resulting number by excluding digits that appear an odd number of times.
import java.util.HashMap;
import java.util.Map;
public class ClearDigitsOut {
public static String clearOddDigits(int n) {
// Convert the integer to a string to work with individual digits
String numStr = Integer.toString(n);
// Map to count frequency of each digit
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char digit : numStr.toCharArray()) {
frequencyMap.put(digit, frequencyMap.getOrDefault(digit, 0) + 1);
}
// StringBuilder to construct the result
StringBuilder result = new StringBuilder();
for (char digit : numStr.toCharArray()) {
if (frequencyMap.get(digit) % 2 == 0) { // Even count
result.append(digit);
}
}
return result.toString();
}
public static void main(String[] args) {
int n = 122334;
System.out.println(clearOddDigits(n)); // Output should be "2233"
}
}
This solution provides an efficient method to solve the problem as the operations are linear in terms of the number of digits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?