我必須創建一個函式,該函式將兩個數字作為引數并將它們相加以獲得一個新數字。然后,該函式將新數字的數字反復相乘,產生一個新數字,直到乘積只有 1 位數字長。回傳最終產品。
例子:
sumDigProd(16, 28) ? 6
--------------------
// 16 28 = 44
// 4 * 4 = 16
// 1 * 6 = 6
我必須對輸入中的數字求和,但在此之后我發現創建這個演算法很困難。
提前致謝
uj5u.com熱心網友回復:
這將是一種解決方案:
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);
}
然后像這樣呼叫你的函式:
sumDigProd(16, 28, true)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/355499.html
