Java interview question:
When deciding whether a number is odd or even, which way should you choose to judge? The code is as follows ()
A:
int val=//A digital
if (val%2==0)
System.out.println ("even");
else
System.out.println ("odd");
B:
int val=//A digital
if (val%2==1)
System.out.println ("odd");
else
System.out.println ("even");
A lot of people will think that these 2 ways are the same. Fact When an integer is greater than 0. The results are consistent in 2 ways. But when the integer is less than 0, the result is divided.
The way to choose A is -1%2 1 is not equal to 0 so he is right for odd numbers. But the way of choosing B and -1%2 is not equal to 1 so the result-1 is even.
So why is there such a mistake in the B way? The underlying algorithm for modulo operations is
A%b--------------------return A-(A/b) *
Then the -1%2 result is of course-1. So the judgment statement goes into else, causing the result of-even 1.