The 30 second answer
I walk the array once and add every integer whose absolute value is between 10 and 99 inclusive. That includes negatives, so 2, 5, minus 66 and 23 sum to minus 43. Single-digit values, numbers with three or more digits, and zero are skipped. The work is linear time and constant extra space. A check that only tests whether n is greater than 9 and less than 100 would drop the negative two-digit values.
Reported as the third question on the same November 2020 Codility test, by a link to a Stack Overflow problem whose title and examples are the statement.
Problem. Given an array of integers, return the sum of those elements that have exactly two digits. The linked problem includes negatives: a two-digit integer is one whose absolute value is between 10 and 99 inclusive.
Examples from that problem:
{1, 23, 4, 55}→23 + 55 = 78{2, 5, -66, 23}→-66 + 23 = -43
Inferred constraints: one pass is enough; the array may be empty (the sum is 0); overflow is not discussed — use long if values can be large in aggregate.
Approach. For each n, if Math.abs(n) is in [10, 99], add n. Time O(n), extra space O(1). A comment on the Zalando thread showed a scan that adds n only when n > 9 && n < 100. That drops every negative two-digit value and does not match the linked statement.
public class SumTwoDigit {
static int sumTwoDigit(int[] a) {
int sum = 0;
for (int n : a) {
int abs = Math.abs(n);
if (abs >= 10 && abs <= 99) sum += n;
}
return sum;
}
public static void main(String[] args) {
System.out.println(sumTwoDigit(new int[] {1, 23, 4, 55})); // 78
System.out.println(sumTwoDigit(new int[] {2, 5, -66, 23})); // -43
System.out.println(sumTwoDigit(new int[] {9, 100, -9, -100, 0})); // 0
}
}Verified with OpenJDK 21.0.13: it prints 78, -43 and 0. Note that Math.abs(Integer.MIN_VALUE) overflows; that value is not two-digit, and it does not appear in the linked examples.
Edge cases. Empty array; no two-digit values; -10 and 99 on the boundaries; 100 and -100, which have three digits; a positive-only check that misses negatives.