Home > Enterprise >  How can I create a function that returns Product of Digit Of Sum of a number
How can I create a function that returns Product of Digit Of Sum of a number

Time:11-11

I have to create a function that takes two numbers as arguments and adds them together to get a new number. The function then repeatedly multiplies the digits of the new number by each other, yielding a new number, until the product is only 1 digit long. Return the final product.

Example:

sumDigProd(16, 28) ➞ 6
--------------------
// 16   28 = 44
// 4 * 4 =  16
// 1 * 6 = 6

I have to sum the numbers in input, but after this i find difficulty to create this algorithm.
Thanks in advance

CodePudding user response:

This would be one solution:

public int sumDigProd(int nr1, int nr2, boolean initial)
{
    int current = nr1 * nr2;
    if(initial)
    {
        current = nr1   nr2;
    }

    if(current / 10 % 10 == 0)
    {
        return current;
    }

    int secondDigit = current % 10;
    int firstDigit = current/10 % 10;

    return sumDigProd(firstDigit, secondDigit, false);
}

Then call your function like this:

sumDigProd(16, 28, true)
  • Related