I feel stupid asking such a simple question, but is there an easy way to determine whether an Integer is even or odd?
+7
A:
if ((n % 2) == 0) {
// number is even
}
else {
// number is odd
}
Richard Fearn
2010-09-29 21:04:35
+3
A:
You can use modular division (technically in Java it acts as a strict remainder operator; the link has more discussion):
if ( ( n % 2 ) == 0 ) {
//Is even
} else {
//Is odd
}
eldarerathis
2010-09-29 21:04:57
+3
A:
If you do a bitwise-and with 1
, you can detect whether the least significant bit is 1. If it is, the number is odd, otherwise even.
In C-ish languages, bool odd = mynum & 1;
This is faster (performance-wise) than mod
, if that's a concern.
mtrw
2010-09-29 21:05:33
wouldn't even be true when mynum is odd?
Bill James
2010-09-29 21:06:37
I think this is flawed. You need to rename your variable to odd.
Anton
2010-09-29 21:16:18
@Bill, @Anton - sorry, I had posted with the wrong sense for the result. I thought I had edited before anyone caught me...
mtrw
2010-09-29 21:20:55
+4
A:
It's not exactly android specific, but a pretty standard function would be:
boolean isOdd( int val ) { return (val & 0x01) != 0; }
Bill James
2010-09-29 21:05:52
A:
When somehow %
as an operator doesn't exist, you can use the AND operator:
oddness = (n & 1) ? 'odd' : 'even'
littlegreen
2010-09-29 21:08:04