I think my solution (which is below) works if I can figure out how to stop the 0 index out of bounds 0 exception which I tried with
ArrayList<Long> exception = new ArrayList<Long>();
if(sumDigits == 0 || numDigits == 0) {
exception.add(0L);
return exception;
}
but I am not sure what I am doing wrong, can someone look at my code and see where I am going wrong? (the long to sum method by the way just gets the sum of the long at that point by the way).
import java.util.*;
class HowManyNumbers {
public static List<Long> findAll(final int sumDigits, final int numDigits) {
ArrayList<Long> exception = new ArrayList<Long>();
if(sumDigits == 0 || numDigits == 0) {
exception.add(0L);
return exception;
}
ArrayList<Long> numbers = new ArrayList<Long>();
for(long i = 0; i < Math.pow(10, numDigits)-1; i++) {
if(LongToSum(i) == sumDigits) {
numbers.add(i);
}
}
ArrayList<Long> ans = new ArrayList<Long>(3);
ans.add(Long.valueOf(numbers.size()));
ans.add(numbers.get(0));
Long last = Long.valueOf(numbers.get(numbers.size()-1));
ans.add(last);
return ans;
}
public static int LongToSum(long num) {
int sum = 0;
if(num != 0) {
long temp = num % 10;
num /= 10;
LongToSum(num);
sum += temp;
}
return sum;
}
}
The link to the original problem: https://www.codewars.com/kata/5877e7d568909e5ff90017e6/train/java (if you wanna see the test cases you can try it out yourself, too.) Not really sure if this is good formatting, but here it is.