The problem in question is a coding challenge from Hackerrank:
Problem Statement
You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our answer is 2.
Note
If the same number is repeated twice at different positions, it should be counted twice, e.g., For N=122, 2 divides 122 exactly and occurs at ones' and tens' position. So for this case, our answer is 3. Division by 0 is undefined. Input Format
The first line contains T (the number of test cases), followed by T lines (each containing an integer N).
Constraints
1≤T≤15
0 < N <10 ^ 10Output Format
For each test case, display the count of digits in N that exactly divide N in a separate line.
Here's my code:
package algorithms.Warmup;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by user1 on 4/2/15.
*/
public class FindDigitsTest {
static Scanner sc = new Scanner(System.in);
private static Long[] findDigits(long num) {
ArrayList<Long> digits = new ArrayList<>();
//extract all digits from input number and store in arraylist
while (num > 0) {
long quotient = num / 10;
long remainder = num - (quotient * 10);
num = quotient;
digits.add(remainder);
}
Long[] result = new Long[digits.size()];
result = digits.toArray(result) ;
return result;
}
private static int findCount(Long[] list, long num) {
int count = 0;
for(int i = 0; i < list.length; i++) {
//ignore division by zero- DON'T FORGET!!!
if(list[i] == 0) {
continue;
}
if (num % list[i] == 0){
count++;
}
}
return count;
}
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
//read in number of test cases
System.out.println("Enter number of test cases: ");
int T = sc.nextInt();
//loop through number of test cases
for(int i = 0; i < T; i++) {
System.out.println("Enter the number: ");
long N = sc.nextLong();
//extract digits of number and store in array
Long[] nDigits = findDigits(N);
//calculate num. of digits which exactly divide N
int answer = findCount(nDigits, N);
//store answer in final arraylist
al.add(answer);
}
//loop through final arraylist to print answers
for(int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
}
}
Even though the submission is correct, and the output is as desired, I feel there are many ways this can be improved, I just don't know how. I see that I have too many ArrayLists and Arrays here and there throughout the code, maybe that can be replaced to begin with.
I'm not completely proficient in Java yet, so my knowledge of Java APIs and Collections is still somewhat limited. That might be one reason for the inefficient code.