| about | help | code help+videos | done | prefs |
public boolean isOddNumber(int n)
boolean odd = false; // default
if (n % 2 != 0) {
odd = true;
}
return odd;
This next section of problems use the MOD or REMAINDER operation,
which uses the percent sign %.
There are actually TWO answers when you divide one number (a dividend)
by another (a divisor): a QUOTIENT and a REMAINDER.
For example: 52 divided by 10 gives 5 with a remainder of 2.
In Java, we have TWO different operations for INTEGERS (not floats or doubles):
QUOTIENT division, which uses a FORWARD SLASH (/), and
REMAINDER division, which used the PERCENT SIGN (%).
Therefore:
52 / 10 gives 5 (the QUOTIENT)
52 % 10 give 2 (the REMAINDER)
The REMAINDER operation has many uses.
1. You can test for an EVEN number by checking that
the remainder is 0 when you divide by 2, e.g. 8 % 2 == 0.
Therefore, given a number n, if (n % 2 == 0), then the number is even.
2. You can test for an ODD number by checking that the
remainder is NOT 0 when you divide by 2, e.g. 7 % 2 != 0
Therefore, given a number n, if (n % 2 != 0), then the number is odd.
This works when n is a NEGATIVE number as well.
NOTE: If n is a POSITIVE number, n % 2 == 1.
HOWEVER: If n is a NEGATIVE number, n % 2 == -1, i.e. the REMAINDER will be -1.
THEREFORE using (n % 2 == 1) to test for an ODD number will not work
when n is NEGATIVE!
3. You can also test whether one number is a factor of the other.
If you divide a number by a DIVISOR and the remainder is zero,
then the divisor is a FACTOR of that number.
Therefore, if n % 6 == 0, then 6 is a FACTOR of n,
and n is a MULTIPLE of 6.
Conversely if n % 6 != 0, then 6 is NOT a FACTOR of n,
and n is NOT a MULTIPLE of 6.
4. Given ANY integer, you can extract the rightmost digit
(the digit in the 1's column) using MOD 10.
For example:
7186 % 10 gives 6
593 % 10 gives 3
14 % 10 gives 4
8 % 10 gives 8, etc.
5. Given any integer, you can extract the 2nd-to-rightmost digit
(the digit in the 10's column) as follows:
(7186 / 10) % 10 give 8
(593 / 10) % 10 gives 9
(25 / 10) % 10 gives 2
(8 / 10) % 10 gives 0
6. Given any integer, you can extract the digit in the 100's columns
as follows:
(7186 / 100) % 10 give 1
(593 / 100) % 10 gives 5
(25 / 100) % 10 gives 0
(8 / 100) % 10 gives 0
isOddNumber(1) → true isOddNumber(2) → false isOddNumber(3) → true ...Save, Compile, Run (ctrl-enter) |
Progress graphs:
Your progress graph for this problem
Random user progress graph for this problem
Random Epic Progress Graph
Difficulty: 1
Copyright Nick Parlante 2017 - privacy