List<Long> to int lossy conversion

62 views Asked by At

I'm trying to solve a challenge and the function must return a long integer and takes an int and List<Long> as parameters but i keep getting the following error:

Solution.java:32: error: incompatible types: possible lossy conversion from long to int
                if (i >= coin) dp[i] += dp[i - coin];

I've tried different casting but it all comes back to this. My code is below:

public static long count(int n, List<Long> c) {


    long[] dp = new long[n + 1];
    dp[0] = 1;

    for (long coin : c) {
        for (long i = 1; i <= n; i++){
            if (i >= coin) dp[i] += dp[i - coin];
         }
     }
    return dp[n];

   }

}
1

There are 1 answers

0
Anil M On

Couple problems here:

  1. i should be an int and not a long since it is the variable initialized in a for loop. If it was a long, you'd get a type mismatch error.

  2. Since c stores instances of Long, coin should also be a Long

Now, since i is an int and coin is a Long, you need to cast the difference of the two to an int as well.

public static long count(int n, List<Long> c) {
    long[] dp = new long[n + 1];
    dp[0] = 1;
    for (Long coin : c) {
        for (int i = 1; i <= n; i++) {
            if (i >= coin) dp[i] += dp[(int) (i - coin)];
        }
    }
    return dp[n];
}