Basic Number Logic
Solve one Java logic problem at a time, then flip for the complete explanation and program.
Solve one Java logic problem at a time, then flip for the complete explanation and program.
Java Logic Development · Chapter 01 Companion Article
Sixteen foundational number-logic problems — parity checks, comparisons, swapping, summation formulas, powers, and range validation — converted into conditions, formulas, loops, and Java expressions. The same thinking patterns reappear later in arrays, strings, collections, and validation logic.
Basic number problems are useful for learning how to convert a requirement into conditions, formulas, loops, and Java expressions. Although many of these problems are small, the same thinking patterns appear later in arrays, strings, collections, validation logic, and real application code.
| Pattern | Used For |
|---|---|
| Modulo operator | Even/odd, remainder-based logic |
| Comparison operators | Positive/negative, maximum, minimum |
| Temporary storage | Swapping values |
| Arithmetic transformation | Swap without third variable |
| Conditional operator | Absolute value and simple decisions |
| Accumulator variable | Number summation |
| Mathematical formula | Optimized summation |
| Loop | Tables, powers, repeated calculations |
| Division and modulo | Quotient and remainder |
| Logical AND | Range validation |
An integer is even if it is exactly divisible by 2, and odd if division by 2 leaves a non-zero remainder. The modulo operator % returns the remainder after division.
For an integer number, number % 2 == 0 means the number is even. Otherwise, it is odd.
Every integer can be represented in one of these forms: 2 × k or 2 × k + 1, where k is another integer. Numbers of the first form are even. Numbers that leave a remainder after division by 2 are odd.
For number = 27, the calculation 27 % 2 = 1 leaves a remainder, so 27 is odd.
public class EvenOddExample {
public static void main(String[] args) {
int number = 27;
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
27 is odd.
| Step | Value |
|---|---|
| number | 27 |
| number % 2 | 1 |
| 1 == 0 | false |
| Executed block | else |
| Result | Odd |
Zero is even because 0 % 2 = 0.
The same condition works for negative integers. For -8 % 2 = 0, therefore -8 is even.
O(1) — only one modulo operation and one comparison are required.
O(1) — no additional data structure is required.
number % 2 == 1 for odd numbers without considering negative values.A safer test for odd numbers is number % 2 != 0.
When asked whether a number is even or odd, modulo is normally the clearest solution. Bitwise checking with number & 1 is possible, but modulo is easier to understand unless the interviewer specifically asks for a bitwise solution.
A number can belong to exactly one of three groups: positive, negative, or zero. The classification depends on comparison with zero.
number > 0 means positive. number < 0 means negative. If neither condition is true, the number must be zero.
public class NumberSignExample {
public static void main(String[] args) {
int number = -12;
if (number > 0) {
System.out.println("Positive number");
} else if (number < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
}
}
Negative number
number = -12
-12 > 0 -> false
-12 < 0 -> true
Result: Negative number
The three possible outcomes are mutually exclusive. Once Java finds a true condition, the remaining conditions do not need to be evaluated.
Important values include Integer.MAX_VALUE, Integer.MIN_VALUE, and 0. The comparison logic works correctly for all three.
O(1)
O(1)
Do not write independent conditions when only one result is expected unless there is a specific reason. For example, an if-else-if chain communicates the requirement more clearly than three separate if statements.
This problem tests basic conditional reasoning. Explain the three mutually exclusive states instead of simply presenting the code.
Finding the maximum means determining which of two supplied values is greater. For a = 48 and b = 35, the maximum is 48.
Compare a > b. If true, a is greater. Otherwise, b is greater or both values are equal.
public class MaximumOfTwo {
public static void main(String[] args) {
int a = 48;
int b = 35;
int maximum;
if (a > b) {
maximum = a;
} else {
maximum = b;
}
System.out.println("Maximum = " + maximum);
}
}
Maximum = 48
| Variable | Value |
|---|---|
| a | 48 |
| b | 35 |
| a > b | true |
| maximum | 48 |
Suppose a = 20 and b = 20. The condition a > b becomes false, so b is assigned to maximum. The result is still correct because both numbers have the same value.
For a simple comparison, int maximum = a > b ? a : b; is concise, but a normal if-else block can be easier for beginners to debug.
Java provides Math.max(a, b). For production code, this is often preferable when no custom logic is required.
O(1)
O(1)
Do not unnecessarily sort two values just to find the maximum. Sorting introduces extra logic for a problem that requires only one comparison.
If an interviewer asks for logic without built-in methods, use a direct comparison. If built-in methods are allowed, Math.max communicates intent clearly.
The maximum of three values can be found by keeping track of the largest value encountered so far. For a = 17, b = 42, c = 29, the maximum is 42.
Start by assuming the first value is maximum: maximum = a. Compare b with maximum, then compare c with the updated maximum.
public class MaximumOfThree {
public static void main(String[] args) {
int a = 17;
int b = 42;
int c = 29;
int maximum = a;
if (b > maximum) {
maximum = b;
}
if (c > maximum) {
maximum = c;
}
System.out.println("Maximum = " + maximum);
}
}
Maximum = 42
maximum = 17
42 > 17 -> true -> maximum = 42
29 > 42 -> false -> maximum = 42
Final: maximum = 42
The same technique scales naturally to arrays. Instead of writing complicated combinations such as a > b && a > c, you can maintain a running maximum. That technique is later used for:
int maximum = Math.max(a, Math.max(b, c)); is compact but hides the underlying comparison logic.
For 50, 50, 20, the result remains 50. The problem normally requires the maximum value, not which variable contains it.
O(1)
O(1)
The running-maximum approach demonstrates logic that can later be generalized from three numbers to any number of values.
When multiple values are available, finding the minimum means identifying the smallest value among them. A common technique is to assume the first value is currently the minimum and update it whenever a smaller value appears. For 18, 7, 42, -3, 11, the minimum is -3.
public class MinimumNumber {
public static void main(String[] args) {
int[] numbers = {18, 7, 42, -3, 11};
int minimum = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < minimum) {
minimum = numbers[i];
}
}
System.out.println("Minimum = " + minimum);
}
}
Minimum = -3
Starting value: minimum = 18
| Current Number | Current Minimum | Updated Minimum |
|---|---|---|
| 7 | 18 | 7 |
| 42 | 7 | 7 |
| -3 | 7 | -3 |
| 11 | -3 | -3 |
Final minimum: -3
Using minimum = 0 would produce incorrect results when all supplied numbers are positive. For example, in 4, 8, 15 zero is not present in the input, but the algorithm might incorrectly keep zero as the minimum. Initializing from actual input avoids this problem.
The array must contain at least one element before accessing numbers[0]. For reusable methods, empty input should be validated.
For n values, O(n) — every number may need to be checked once.
The minimum-search logic itself uses O(1) additional space.
Sorting the complete collection just to retrieve the smallest element is unnecessary. Linear scanning is sufficient when only the minimum is needed.
This is a fundamental tracking-variable pattern. The same logic is reused in many interview problems.
Swapping means exchanging the values stored in two variables. Before: a = 10, b = 25. After: a = 25, b = 10.
If you immediately write a = b, the original value of a is lost. A temporary variable protects that value.
temp = a
a = b
b = temp
public class SwapNumbers {
public static void main(String[] args) {
int a = 10;
int b = 25;
System.out.println("Before swap: a = " + a + ", b = " + b);
int temp = a;
a = b;
b = temp;
System.out.println("After swap: a = " + a + ", b = " + b);
}
}
Before swap: a = 10, b = 25
After swap: a = 25, b = 10
a = 10, b = 25
temp = a -> temp = 10
a = b -> a = 25
b = temp -> b = 10
O(1)
O(1) — one temporary variable uses constant additional memory.
Swapping appears in algorithms such as:
Incorrect sequence: a = b; b = a; — after the first statement, the original a has already been overwritten.
Using a temporary variable is normally the safest and most readable solution. Avoid complicated tricks unless the interviewer explicitly asks for swapping without additional storage.
Two integer values can be exchanged without declaring another variable. One arithmetic technique uses addition and subtraction.
Starting with a = 12, b = 30, perform:
a = a + b
b = a - b
a = a - b
public class SwapWithoutThirdVariable {
public static void main(String[] args) {
int a = 12;
int b = 30;
System.out.println("Before swap: a = " + a + ", b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swap: a = " + a + ", b = " + b);
}
}
Before swap: a = 12, b = 30
After swap: a = 30, b = 12
a = 12, b = 30
a = 12 + 30 = 42
b = 42 - 30 = 12
a = 42 - 12 = 30
Final: a = 30, b = 12
After a = a + b, the new a contains information about both original values. Subtracting the old b retrieves the original a. The final subtraction retrieves the original b.
The statement a = a + b can overflow when both values are large — the mathematical sum may exceed the range supported by int. Because of this, arithmetic swapping is normally not recommended for production Java code.
Integers can also be swapped using XOR:
a = a ^ b;
b = a ^ b;
a = a ^ b;
This avoids arithmetic overflow but is less readable.
In normal application code, prefer a temporary variable. No-third-variable swapping is mainly useful as a logic or interview exercise.
O(1)
O(1)
Mention the overflow limitation of addition/subtraction swapping. That demonstrates stronger understanding than simply memorizing the three statements.
Absolute value represents the distance of a number from zero, regardless of direction. Examples: |8| = 8, |-8| = 8, |0| = 0.
If the number is negative, reverse its sign. Otherwise, keep it unchanged.
public class AbsoluteValueExample {
public static void main(String[] args) {
int number = -45;
long absoluteValue = number < 0 ? -(long) number : number;
System.out.println("Absolute value = " + absoluteValue);
}
}
Absolute value = 45
number = -45
number < 0 -> true
-(long) -45 -> 45
absoluteValue = 45
The int range is -2147483648 to 2147483647. The positive equivalent of -2147483648 is 2147483648, which cannot fit inside int. Casting to long before negation allows this value to be represented safely.
Java provides Math.abs(number). This is appropriate in most normal code. However, Math.abs(Integer.MIN_VALUE) still returns a negative int because its positive equivalent cannot be represented by int.
O(1)
O(1)
Absolute difference is commonly used for:
Example: Math.abs(actual - expected)
Do not blindly use number = -number for every negative int without considering Integer.MIN_VALUE.
For basic questions, explain the sign check. For stronger answers, also mention the Integer.MIN_VALUE edge case.
Natural-number summation usually means adding consecutive positive integers from 1 to n. For n = 5, the sum is 1 + 2 + 3 + 4 + 5 = 15.
A direct approach is to maintain an accumulator, sum = sum + i, for every value from 1 through n.
The sum can also be calculated directly: n × (n + 1) / 2.
For numbers 1, 2, 3, ..., n, pairing values from opposite ends produces repeated sums of n + 1. This leads to the formula n(n + 1) / 2.
public class NaturalNumberSum {
public static void main(String[] args) {
int n = 10;
long sum = (long) n * (n + 1) / 2;
System.out.println("Sum = " + sum);
}
}
Sum = 55
n = 10
10 x 11 / 2 = 110 / 2 = 55
The expression n * (n + 1) is calculated as int if both operands are int. It may overflow before the result is stored in long. Therefore (long) n * (n + 1) forces the multiplication to use long arithmetic.
long sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
This is useful when learning loops, but the formula is faster when only the final sum is required.
Loop: time O(n), space O(1). Formula: time O(1), space O(1).
If the requirement defines natural numbers as positive integers, n should satisfy n >= 1. Some systems also include zero in natural numbers, so requirements should be clarified.
When asked to optimize a summation problem, recognize whether a mathematical formula can replace iteration.
Find the sum of all even integers from 1 through n. For n = 10, even numbers are 2, 4, 6, 8, 10 and the sum is 30.
Check every number with i % 2 == 0 and add matching values. A better loop can skip odd numbers completely using i += 2.
The first k positive even numbers are 2, 4, 6, ..., 2k. Their sum is k(k + 1). When the range is 1 through n, k = n / 2 because integer division gives the number of even values in the range.
public class EvenNumberSum {
public static void main(String[] args) {
int n = 10;
long count = n / 2;
long sum = count * (count + 1);
System.out.println("Sum of even numbers = " + sum);
}
}
Sum of even numbers = 30
n = 10
count = 10 / 2 = 5
5 x 6 = 30
For n = 9, even values are still 2, 4, 6, 8. Integer division gives 9 / 2 = 4, so the formula continues to work.
long sum = 0;
for (int i = 2; i <= n; i += 2) {
sum += i;
}
Formula: O(1). Loop: O(n) — more precisely, the loop executes roughly n / 2 times, which still simplifies to O(n).
Do not confuse sum of even numbers up to n with sum of the first n even numbers — these are different requirements. For the first n even numbers, n itself represents the count.
Clarify whether n represents an upper range limit or the number of even terms before writing the algorithm.
Find the sum of all odd integers between 1 and n. For n = 10, odd values are 1, 3, 5, 7, 9 and the sum is 25.
The sum of the first k odd numbers is k². For a range from 1 through n, the number of odd values is (n + 1) / 2 using integer division.
public class OddNumberSum {
public static void main(String[] args) {
int n = 10;
long count = ((long) n + 1) / 2;
long sum = count * count;
System.out.println("Sum of odd numbers = " + sum);
}
}
Sum of odd numbers = 25
n = 10
count = (10 + 1) / 2 = 11 / 2 = 5
5 x 5 = 25
1 = 1^2
1 + 3 = 2^2
1 + 3 + 5 = 3^2
1 + 3 + 5 + 7 = 4^2
Each new odd number expands the previous square into the next square.
long sum = 0;
for (int i = 1; i <= n; i += 2) {
sum += i;
}
Formula: O(1). Loop: O(n).
For negative ranges, this formula is not applicable without redefining the problem. It assumes a positive range beginning at 1.
Recognizing numeric patterns can eliminate unnecessary loops. Explain the count of odd numbers before applying the square formula.
A multiplication table repeatedly multiplies one fixed number by a sequence of integers. For 7: 7 × 1 through 7 × 10. This is a straightforward example of counted iteration.
public class MultiplicationTable {
public static void main(String[] args) {
int number = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + number * i);
}
}
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
For the first three iterations:
| i | Calculation | Result |
|---|---|---|
| 1 | 7 × 1 | 7 |
| 2 | 7 × 2 | 14 |
| 3 | 7 × 3 | 21 |
The loop continues until i becomes 11. At that point i <= 10 becomes false.
The fixed number whose table is generated.
Controls the multiplier and loop count.
A reusable version can accept a starting multiplier, ending multiplier, and table number — for example, 5 × 6 through 5 × 15. This demonstrates that the algorithm is not restricted to 1 through 10.
If the table contains k entries, O(k). For a fixed table of 10 entries, it can technically be viewed as constant work, but O(k) better describes the generalized solution.
O(1)
i < 10 when the table should include 10.Simple loop questions often test boundary handling. Pay attention to starting value, ending value, and whether the limits are inclusive.
For a non-negative integer exponent, power represents repeated multiplication. For 3⁴, the calculation is 3 × 3 × 3 × 3 = 81. Here 3 is the base, 4 is the exponent, and 81 is the result.
Start with result = 1, then multiply result by the base exponent times.
One is the multiplicative identity. For any value x, 1 × x = x. Starting with zero would make every multiplication remain zero.
public class PowerExample {
public static void main(String[] args) {
int base = 3;
int exponent = 4;
long result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
System.out.println("Result = " + result);
}
}
Result = 81
Initial: result = 1
| Iteration | Calculation | result |
|---|---|---|
| 1 | 1 × 3 | 3 |
| 2 | 3 × 3 | 9 |
| 3 | 9 × 3 | 27 |
| 4 | 27 × 3 | 81 |
By definition x⁰ = 1 for non-zero x. The loop executes zero times, leaving result = 1, which naturally handles this case.
A negative exponent creates a fractional result — for example 2⁻² = 1 / 4. The current integer-based algorithm intentionally handles only exponent >= 0. A double-based implementation would be needed for negative exponents.
Java provides Math.pow(base, exponent). It returns a double. For integer-only logic problems, manual multiplication makes the algorithm easier to study.
Exponentiation by squaring can reduce the complexity from O(exponent) to O(log exponent). For example, 2¹⁰ does not need ten separate multiplications if repeated squaring is used.
Basic loop: O(exponent)
O(1)
Initializing result = 0 causes every positive exponent result to remain zero.
Start with the simple iterative solution. If the exponent may be very large, discuss exponentiation by squaring as an optimization.
The square of a number is the number multiplied by itself once: square = n × n. The cube multiplies the number three times: cube = n × n × n.
For n = 6: square 6 × 6 = 36, cube 6 × 6 × 6 = 216.
public class SquareCubeExample {
public static void main(String[] args) {
int number = 6;
long square = (long) number * number;
long cube = (long) number * number * number;
System.out.println("Square = " + square);
System.out.println("Cube = " + cube);
}
}
Square = 36
Cube = 216
number = 6
Square: 6 x 6 = 36
Cube: 6 x 6 x 6 = 216
Using Math.pow(number, 2) works, but Math.pow returns double. For exact integer square and cube calculations, direct multiplication is simpler and avoids floating-point conversion.
For number = -3: square (-3) × (-3) = 9, cube (-3) × (-3) × (-3) = -27. The normal multiplication rules automatically produce the correct signs.
Even long has a finite range. Large values can overflow during square or cube calculations. For arbitrary-size integer calculations, Java provides BigInteger.
O(1)
O(1)
Casting before the first multiplication is useful when the input is int but the result is stored in long.
Integer division can produce two useful values: quotient, how many complete times the divisor fits into the dividend, and remainder, what remains after those complete divisions. For 29 ÷ 6, the quotient is 4 and the remainder is 5, because 29 = 6 × 4 + 5.
Division operator /. Modulo operator %.
public class QuotientRemainderExample {
public static void main(String[] args) {
int dividend = 29;
int divisor = 6;
int quotient = dividend / divisor;
int remainder = dividend % divisor;
System.out.println("Quotient = " + quotient);
System.out.println("Remainder = " + remainder);
}
}
Quotient = 4
Remainder = 5
dividend = 29, divisor = 6
29 / 6 = 4
6 x 4 = 24
29 - 24 = 5
quotient = 4, remainder = 5
For integer division: dividend = divisor × quotient + remainder. For this example: 29 = 6 × 4 + 5.
The divisor must never be zero. This causes ArithmeticException for integer division. A reusable method should validate divisor != 0 before calculating.
Java integer division removes the fractional portion. For 7 / 2, the result is 3, not 3.5. To obtain a decimal result, at least one operand must use a floating-point type.
Java allows negative operands. For example, -29 % 6 produces -5. Java's remainder has the same sign as the dividend when the result is non-zero.
Modulo logic appears in:
O(1)
O(1)
Do not assume integer division automatically produces a decimal result. int result = 5 / 2; produces 2.
Be prepared to explain the relationship between quotient, remainder, dividend, and divisor instead of only naming the two operators.
Range validation determines whether a value falls between allowed lower and upper limits. Suppose a valid age must be between 18 and 60 inclusive. A value is valid only if both age >= 18 and age <= 60 are true.
Use logical AND: number >= minimum && number <= maximum. Both conditions must be true.
public class RangeValidation {
public static void main(String[] args) {
int number = 24;
int minimum = 18;
int maximum = 60;
if (number >= minimum && number <= maximum) {
System.out.println(number + " is within range " + minimum + " to " + maximum + ".");
} else {
System.out.println(number + " is outside the valid range.");
}
}
}
24 is within range 18 to 60.
number = 24, minimum = 18, maximum = 60
24 >= 18 -> true
24 <= 60 -> true
true && true -> true
Result: 24 is accepted.
The condition number >= minimum && number <= maximum includes both boundary values. For a range 18 through 60, 18 is valid and 60 is also valid.
To exclude the boundaries: number > minimum && number < maximum. Now only values strictly between the limits are valid.
Minimum inclusive, maximum exclusive: number >= minimum && number < maximum. This style is common in:
Consider number >= minimum || number <= maximum. Using OR would usually make the condition almost always true. For a valid bounded range, the value must satisfy both lower and upper constraints.
When minimum and maximum come from external input, verify minimum <= maximum. A range such as minimum = 100, maximum = 20 is logically invalid.
public class RangeValidator {
public static boolean isWithinRange(int number, int minimum, int maximum) {
if (minimum > maximum) {
return false;
}
return number >= minimum && number <= maximum;
}
public static void main(String[] args) {
System.out.println(isWithinRange(35, 10, 50));
}
}
true
O(1)
O(1)
Range validation appears frequently in real applications:
> when the minimum should be allowed.< when the maximum should be allowed.Always clarify whether the boundaries are inclusive or exclusive. Many range-validation bugs come from incorrect boundary assumptions.
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Remainder | a % b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal | a >= b |
<= | Less than or equal | a <= b |
== | Equal to | a == b |
!= | Not equal to | a != b |
&& | Logical AND | a >= min && a <= max |
|| | Logical OR | a < min || a > max |
Used when a decision depends on relative numeric values. Examples: maximum, minimum, positive or negative, range checking.
if (a > b) {
// Handle greater value
}
Use modulo when the problem depends on divisibility. Typical form: number % divisor. Common uses: even or odd, divisibility, last digit, circular operations.
Maintain the best value found so far, for example int maximum = numbers[0];, then update it when a better candidate appears. This pattern later becomes important in:
An accumulator collects a result over multiple iterations.
long sum = 0;
for (...) {
sum += value;
}
Common uses: sum, count, product, average preparation, frequency calculations.
Before writing a loop, determine whether the same result can be calculated directly. Instead of summing 1 + 2 + 3 + ... + n, use n × (n + 1) / 2. This changes the time complexity from O(n) to O(1).
Many bugs occur at boundary values. For a range 10 to 50, test at least 9, 10, 11, 49, 50, 51. This verifies both inside and outside conditions.
Choosing an appropriate numeric type matters when calculations can become large.
| Type | Approximate Use |
|---|---|
byte | Very small integer values |
short | Small integer values |
int | Normal integer calculations |
long | Larger integer calculations |
float | Lower-precision decimal calculations |
double | General decimal calculations |
BigInteger | Arbitrarily large integers |
BigDecimal | Precise decimal arithmetic |
For most beginner number-logic problems, int is enough for input. Intermediate calculations may require long.
Java does not automatically stop integer overflow.
int a = Integer.MAX_VALUE;
int b = a + 1;
The result wraps around to the negative side of the int range. This matters especially in:
A common defensive technique is to promote the operation before multiplication:
long result = (long) a * b;
Casting after multiplication may be too late because overflow may already have happened.
Different problems can often be solved in more than one way.
| Problem | Loop | Formula/Direct Logic |
|---|---|---|
| Even/Odd | Not needed | O(1) |
| Maximum of two | Not needed | O(1) |
| Sum 1 to n | O(n) | O(1) |
| Sum even numbers | O(n) | O(1) |
| Sum odd numbers | O(n) | O(1) |
| Multiplication table | O(n) | Normally requires iteration |
| Power | O(n) basic | O(log n) optimized |
| Range validation | Not needed | O(1) |
Use a loop when repeated processing is genuinely required. Use direct arithmetic when a reliable formula exists.
Number logic becomes more reliable when assumptions are explicit.
Before dividend / divisor, ensure divisor != 0.
Before using minimum <= number && number <= maximum, ensure minimum <= maximum.
If a problem only supports positive n, n > 0 should be part of the requirement.
If an integer power algorithm only handles non-negative exponents, exponent >= 0 must be guaranteed or checked.
Useful test values include:
| Test Value | Why It Matters |
|---|---|
| 0 | Boundary between positive and negative |
| 1 | Smallest common positive value |
| -1 | Small negative value |
| Even positive | Parity test |
| Odd positive | Parity test |
| Even negative | Negative parity |
| Odd negative | Negative parity |
| Equal values | Maximum/minimum comparison |
| Integer.MAX_VALUE | Overflow testing |
| Integer.MIN_VALUE | Absolute-value and overflow testing |
| Range minimum | Inclusive boundary |
| Range maximum | Inclusive boundary |
| Just below minimum | Invalid boundary |
| Just above maximum | Invalid boundary |
Requirement: 18 or older. Correct: age >= 18. Incorrect: age > 18 — this rejects exactly 18.
Incorrect: number >= minimum || number <= maximum. Correct: number >= minimum && number <= maximum.
Incorrect sequence: a = b; b = a; — both values may become identical. Protect the original value before overwriting it.
Incorrect: int result = 0; result *= base; — any multiplication by zero remains zero. For repeated multiplication, initialize with result = 1.
Avoid assumptions such as minimum = 0 when zero may not exist in the input. Initialize tracking variables from actual input whenever possible.
5 / 2 produces 2 when both operands are integers. For 2.5, use a floating-point operand.
Risky: long result = a * b; — if both a and b are int, overflow can happen before assignment. Safer: long result = (long) a * b;
Before coding a number-logic problem, identify:
| Topic | Typical Time | Extra Space |
|---|---|---|
| Even or Odd | O(1) | O(1) |
| Positive, Negative or Zero | O(1) | O(1) |
| Maximum of Two | O(1) | O(1) |
| Maximum of Three | O(1) | O(1) |
| Minimum of Multiple Numbers | O(n) | O(1) |
| Swap Two Numbers | O(1) | O(1) |
| Swap Without Third Variable | O(1) | O(1) |
| Absolute Value | O(1) | O(1) |
| Sum of Natural Numbers | O(1) with formula | O(1) |
| Sum of Even Numbers | O(1) with formula | O(1) |
| Sum of Odd Numbers | O(1) with formula | O(1) |
| Multiplication Table | O(n) | O(1) |
| Power of Number | O(n) basic | O(1) |
| Square and Cube | O(1) | O(1) |
| Quotient and Remainder | O(1) | O(1) |
| Number Range Validation | O(1) | O(1) |
After understanding the basic implementations, useful variations include: