0

How to compute the sum of all 'odd digits of an input' using 'loop'. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)

I can't quite figure out how to do that, can someone please help me out. This is what I have done so far, I don't know how to complete it or whether I have its right or wrong.

Any help would be appreciated!

System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();

int sum = 0;
int digits = 0;

for (int i = 0; i < length; i++) {
    if (length % 2 == 1) {
        digits += i;
        sum = digits++;
    }
}
System.out.println(sum);
Aashish Kumar
  • 2,771
  • 3
  • 28
  • 43
chabztar01
  • 61
  • 5
  • 1
    why did you add this check: if(length%2==1){ ? – Stultuske Sep 11 '20 at 08:58
  • Does this answer your question? [Iterate through each digit in a number](https://stackoverflow.com/questions/5009591/iterate-through-each-digit-in-a-number) – OH GOD SPIDERS Sep 11 '20 at 09:02
  • You aren't too far, you found the main logic. Few steps are missing: inside your loop, you need to get the character indexed at `i` (e.g. with `String#charAt`), then you need to convert it into a number (e.g. with `Integer#valueOf`). Only then, you can do your modulo on it to know whether odd or even, and add it to the sum if odd. – sp00m Sep 11 '20 at 09:03

4 Answers4

3

Here comes a Java8-based solution:

final int result = input.chars()//make a stream of chars from string
                        .mapToObj(String::valueOf) // make every character a String to be able to use parseInt later
                        .mapToInt(Integer::parseInt) // transform character in int
                        .filter(i -> i % 2 == 1) // filter out even numbers
                        .sum(); 
EnzoMolion
  • 949
  • 8
  • 25
1

You don't need to use String if your input is not so long. also for safe side use long datatype. Here is the working code with comments (explain each step).

long sumOddDigits(long value){
    long temp = value; // copy in temp variable
    long sum = 0;
    while(temp > 0){
      int digit = temp%10; // get last digit of number. example: 227 gives 7.
      temp = temp / 10; // remove that last digit from number.227 will be 22.
      if(digit % 2 == 1){
        sum += digit;
      }
    }
    return sum;
}
  • I think this is a really nice solution since you don't need any data conversion. If you use this solution you may also use `Scanner.nextInt()` and `Scanner.hasNextInt()` to make sure that the user can only input `Integer` values and catch inputs that are not `Integer` values. – MarkusAnd Sep 11 '20 at 09:12
0

Your interpretation of the digits inside of input is not working this way.

System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();

int sum = 0;

for (int i = 0; i < length; i++) {
    int digit = input.charAt(i) - '0';
    if (digit % 2 == 1) {
        System.out.println("Add digit: " + digit);
        sum += digit;
    }
}
System.out.println(sum);
Milgo
  • 2,617
  • 4
  • 22
  • 37
  • Hi Milgo, what does +1 do exactly in this specific code: Integer digit = Integer.valueOf(input.substring(i, i + 1)); Am just intrested and want to learn – chabztar01 Sep 11 '20 at 09:22
  • 1
    You get a part of input, a sub string, between two indices. You start with the character at index i and end at index i + 1, so in the end you only get one character. I would prefer charAt(i), but that returns a 'char' which is misinterpreted as Integer. – Milgo Sep 11 '20 at 09:26
  • 1
    @Milgo, you could be using `charAt` too, and it would be even simpler to get the digit value: `int digit = input.charAt(i) - '0';` :) – Nowhere Man Sep 11 '20 at 09:35
  • @AlexRudenko The output shows a totally wrong output, am I doing something wrong with your way? – chabztar01 Sep 11 '20 at 09:46
  • @chabztar01, please clarify. Both initial version and the updated one work fine for integer numbers without decimal or thousand separators. Did you try to input a non-integer number containing other characters than digits? – Nowhere Man Sep 11 '20 at 09:55
  • @AlexRudenko I changed it to the following: System.out.println("Enter a number: "); String input = in.nextLine(); int length = input.length(); int sum = 0; for (int i = 0; i < length; i++) { int digit = input.charAt(i); if (digit % 2 == 1) { System.out.println(digit); sum += digit; } } System.out.println(sum); And the output showed the following: Enter a number: 32677, 51, 55, 55, 161 – chabztar01 Sep 11 '20 at 10:15
  • @AlexRudenko sorry, it looks so messy when I put the code in the comment – chabztar01 Sep 11 '20 at 10:17
  • @chabztar01, you need to subtract the value of `'0'` as it is written above to convert a char `'0', '1',..'9'` to integer number `0, 1, 2,.. 9` – Nowhere Man Sep 11 '20 at 10:23
0

In your loop, use Integer.parseInt(input.charAt(i)) to get the number at position i.

if(length%2==1){ that doesn't make sense here. You want to check if your number is odd, not the length of your string.

Ascendise
  • 189
  • 1
  • 10