Write a Java method to count the number of digits in an integer with the value 2. The integer may be assumed to be nonnegative.

Source Code:

public class CountDigitTwo {
public static void main(String[] args) {
int result = countTwos(2252);
System.out.println(result);
}

public static int countTwos(int n) {
int count = 0;
while (n > 0) {
int rem = n % 10;
if (rem == 2) {
count++;
}
n = n / 10;
}
return count;
}
}

Output: