Given an integer X within the range of 0 to 9, and given two positive
integers as upper and lower bounds respectively, find the number of times X occurs as a digit in an integer within the range, excluding the bounds. Print the frequency of occurrence as output.
Input: The first line of input is an integer T, denoting the number of test cases. For each test case, there are two lines of input, first consisting of the integer X, whose occurrence has to be counted. Second, the lower and upper bound, L and U which are positive integers, on the same line separated by a single space, respectively.
Output: For each test case, there is only one line of output, the count of the occurrence of X as a digit in the numbers lying between the lower and upper bound, excluding them.
Constraints: 1<=T<=100 0<=X<=9 0
Example: Input 5 3 100 250 2 10000 12345 0 20 21 9 899 1000 1 1100 1345 Output: 35 1120 0 120 398
Explanation:
In the first test case, the occurrence of 3 in the numbers starting from 101 to 249 is counted and comes out to be 35.
My approach:
/*package whatever //do not write package name here */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class GFG {
private static int numOccurences (int X, int low, int up)
{
String str;
int totOcc = 0;
//Convert a digit 0-9 to a character
char chk = Character.forDigit(X,10);
for (int i = low+1; i < up; i++)
{
str = String.valueOf(i);
totOcc += numCharsInStr(str,chk);
}
return totOcc;
}
private static int numCharsInStr (String str, char ch)
{
int numOccurs = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ch)
{
numOccurs++;
}
}
return numOccurs;
}
public static void main (String[] args) throws IOException {
//code
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String line = br.readLine();
String line2;
String line3;
int numTests = Integer.parseInt(line);
int X;
String [] inps;
int lower;
int upper;
for (int i = 0; i < numTests; i++)
{
line2 = br.readLine();
X = Integer.parseInt(line2);
line3 = br.readLine();
inps = line3.split(" ");
lower = Integer.parseInt(inps[0]);
upper = Integer.parseInt(inps[1]);
System.out.println(numOccurences(X,lower,upper));
}
}
}
I have the following questions with regards to the code:
- How can I further improve my approach?
- Is there a better way to solve this question?
- Are there any grave code violations that I have committed?
- Can space and time complexity be further improved?