-4

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.

  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – f1sh May 23 '22 at 18:02
  • 1
    Welcome. You should take a look at [ask] and take the [tour], if you have not done so already. Also take a look at [example]. – cliff2310 May 23 '22 at 18:37
  • Your attempt to fix the IndexOutOfBoundsException doesn't work because it doesn't happen for `sumDigits == 0` or `numDigits == 0` - it happens when you try to read the minimum answer (`numbers.get(0)`) if your code didn't find any solutions (i.e. `number.size() == 0`). You must fix your code for that case. – Thomas Kläger May 24 '22 at 05:38
  • IMHO the reason that your code doesn't find any solutions is that the `LongToSum()` method doesn't work. To check your code you could add a `main` method with `System.out.println(findAll(10, 3));` in it and then run your code locally in your IDE. – Thomas Kläger May 24 '22 at 05:57

0 Answers0