Reputation: 1
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];
}
}
Upvotes: 0
Views: 62
Reputation: 700
Couple problems here:
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.
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];
}
Upvotes: 1