HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavaModerate

Determining the difference between odd and even numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
determiningthenumbersdifferencebetweenandevenodd

Problem

I have code that converts each character of a String to an int and returns the difference between odd and even numbers. Can this code be simplified?

int compareSumOfDigits(String N) {
int e=0,o=0;
for (int i =0;i<N.length();i++){
    int t = Character.getNumericValue(N.charAt(i));
    if(t%2==0)
    e+=t;
else
    o+=t;

}
      return  o-e ;
}

Solution

Combining some of the existing answers, you can do

s.chars()                          // get the char stream
  .map(Character::getNumericValue) // convert to ints
  .map(n -> n%2==0 ? -n : n)       // negate the even ones
  .sum()                           // sum it all up


This will give you the sum of the odds and the negative evens, which is the same as the sum of the odds minus the sum of the evens.

edit

In response to @kai, for absolute max readability, I'd probably do (pseudocode)

List ints = s.chars().map(Character::getNumericValue)
Map> intsEven = ints.partitioningBy(n -> n%2==0)
return intsEven.get(false).sum() - intsEven.get(true).sum()


or with isEven from the other answers and not defined here

List ints = s.chars().map(Character::getNumericValue)
List evens = ints.filter(isEven)
List odds = ints.filter(not(isEven))
return odds.sum() - evens.sum()

Code Snippets

s.chars()                          // get the char stream
  .map(Character::getNumericValue) // convert to ints
  .map(n -> n%2==0 ? -n : n)       // negate the even ones
  .sum()                           // sum it all up
List<int> ints = s.chars().map(Character::getNumericValue)
Map<Boolean, List<int>> intsEven = ints.partitioningBy(n -> n%2==0)
return intsEven.get(false).sum() - intsEven.get(true).sum()
List<int> ints = s.chars().map(Character::getNumericValue)
List<int> evens = ints.filter(isEven)
List<int> odds = ints.filter(not(isEven))
return odds.sum() - evens.sum()

Context

StackExchange Code Review Q#101861, answer score: 19

Revisions (0)

No revisions yet.