Saksham Goyal
Saksham Goyal

Reputation: 155

foreach loop string to multiply digits together

I am trying to take a number and multiply each digit together. eg: 1234 -> 1x2x3x4 = 24. here is what I have so far. (JAVA)

int sum = 1;
int num = 1234;
String str = Integer.toString(num);
for(String i: str) {
    sum *=Integer.parseInt(i);
}

I am not sure how to use the foreach loop with string arrays.

I understand that a string is just an array of chars so why shouldnt this work?

Upvotes: 1

Views: 1218

Answers (4)

Lavish Kothari
Lavish Kothari

Reputation: 2331

As no one else mentioned, you can also do it using stream-API introduced in Java-8.

public static long findProductOfDigits(String n) {
    return n.chars()
            .map(c -> Character.getNumericValue(c))
            .mapToLong(i -> i)
            .reduce(1l, (a, b) -> a * b);
}

As your input number can grow beyond long (64 bits), so your result can also go beyond int. So we can use long for the result, instead of int. Though this is not the best solution as long result can still overflow. In that case you can consider returning BigInteger.

But I think the main idea is to give this other possibility of using streams.

Upvotes: 0

Gro
Gro

Reputation: 1683

With Java 8 it is just one statement.

int value = Integer.toString(1234).chars()
            .map(c -> Character.getNumericValue(c))             
            .reduce((a, b) -> a * b).getAsInt();

Upvotes: 0

Nick Nikolov
Nick Nikolov

Reputation: 261

A better way of doing it instead of generating a string and iterating it would be taking the last digit and dividing the number by 10 until there are digits left. Sample code:

int product = 1;
int num = 1234;
while(num > 0)
{
    product *= num % 10;
    num /= 10;
}

Hope this helps.

Upvotes: 3

Andre Bahtiar Fauzi
Andre Bahtiar Fauzi

Reputation: 126

First convert the String to char array and then loop over the char array.

for (char ch: str.toCharArray()) {
     sum *= Character.getNumericValue(ch);
}

or

for (char ch: str.toCharArray()) {
     sum *= Integer.parseInt(String.valueOf("" + ch));
}

Upvotes: 1

Related Questions