Instead of counting two sums (of odd and even digits) and returning their difference,
you could use a single sum value,
subtracting a digit's value if it's even and adding if it's odd.
An added benefit of this approach is that you are more protected from integer overflows:
if odd and even digits are interleaved,
the two-sum approach will be much less likely to overflow.
Building on @m0nhawk's version, with further improving the variable names and a few other tidbits:
boolean isEven(int number) {
return (number % 2) == 0;
}
int compareSumOfDigits(String numericString) {
int sum = 0;
for (Character ch : numericString.toCharArray()) {
int digit = Character.getNumericValue(ch);
if (isEven(digit)) {
sum -= digit;
} else {
sum += digit;
}
}
return sum;
}
Or as @tobias_k proposed,
the if-else can be flattened for a more compact form,
but this is less readable so it goes away from "simple",
and I don't recommend it, but here you go anyway:
int compareSumOfDigits(String numericString) {
int sum = 0;
for (Character ch : numericString.toCharArray()) {
int digit = Character.getNumericValue(ch);
sum += digit * (isEven(digit) ? -1 : 1);
}
return sum;
}
Nothing to do with simplicity,
but when playing with an implementation,
it helps to have some JUnit tests handy to verify that the code still works.
A few examples to get you started:
@Test
public void test_compareSumOfDigits_11111111() {
assertEquals(8, compareSumOfDigits("11111111"));
}
@Test
public void test_compareSumOfDigits_22222222() {
assertEquals(-16, compareSumOfDigits("22222222"));
}
@Test
public void test_compareSumOfDigits_12345678() {
assertEquals(-4, compareSumOfDigits("12345678"));
}
e
,o
andN
from a first glance), the code is pretty straightforward and clear. \$\endgroup\$ – m0nhawk Aug 25 '15 at 11:08