Aviv David Malka
Aviv David Malka

Reputation: 39

The sum of certain digits from an input number

I've been trying to sum a certain digit from a number, for example

Number: 5
Input:  54365
Output: The sum of 5's is 10

Second example:

Number: 5
Input:  5437555
Output: The sum of 5's is 20

I've managed to separate the digits yet I couldn't find the condition to sum a certain number (for instance number 5 like the examples).

I'd appreciate to hear your idea of doing it

public static void main(String[] args) {
    int sum = 0;
    int number = MyConsole.readInt("Enter a number:");
    while (number > 0) {
        if (number % 10 == 8) {
            sum += 8;
        } else {
            number /= 10;
        }
    }
    System.out.println("The sum of 8's is:" + sum);
 }

My way of separating the numbers.
Also i have a small program to get input instead of using scanner since we still haven't went through it in class.

Upvotes: 0

Views: 92

Answers (1)

LppEdd
LppEdd

Reputation: 21172

Your requirement seems reasonably clear to me. Given a number

final int number = 5;

And a starting number

final int input = 54365;

The easiest way is to convert that number to a String

final int inputStr = String.valueOf(input);

Then, you can filter each char for it, and sum them

final int sum =
        inputStr.chars()                         // Get a Stream of ints, which represent the characters
                .map(Character::getNumericValue) // Convert a char to its numeric representation
                .filter(i -> i == number)        // Filter for the designated number
                .sum();                          // Sum all the filtered integers

Output: 10


Using the same approach, but with an old-style for loop

final int input = 54365;
final int inputStr = String.valueOf(input);
final int number = 5;
int sum = 0;

for (final char c : inputStr.toCharArray()) {
    final int n = Character.getNumericValue(c);

    if (n == number) {
        sum += number;
    }
}

Your solution can work

int number = 5;
int input = 543655;
int sum = 0;

while (input > 0) {
    if (input % 10 == number) {
        sum += number;
    }

    input /= 10;
}

Upvotes: 1

Related Questions