Devyn Hedin Devyn Hedin - 28 days ago 7
Java Question

Issue subtracting negative numbers in Java

I'm writing a recursive method to compute the sum of all odd numbers in the array. However, my program was adding negative numbers as positive numbers.

if(nums[start] % 2 == 1) {
sum+=nums[start];
return computeSumOfOdd(nums, start + 1, sum);


So I changed my code around to this:

if(nums[start] % 2 == 1) {
if(nums[start] < 0)
sum-=nums[start];
else
sum+=nums[start];
return computeSumOfOdd(nums, start + 1, sum);


It still gives me the same response and I can't figure out what I'm doing wrong.

NPE NPE
Answer

In Java, x % 2 can never equal 1 for negative x (the only possible values for x % 2 are -1 and 0).

Therefore, your two snippets are equivalent: the outer if statement is never entered when nums[start] < 0.

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3

Comments