[英]How am I supposed to write over an array given the number of times it has to be copied in Java
[英]How am I supposed to loop repeatedly over a "function" in Java?
我寫了一個代碼,它接受一個數字並將它的數字相乘,就在這里。
public class Happy
{ public static int findSum(int k)
{
int sum = 0;
while (k != 0)
{
sum = sum + ((k % 10)*(k % 10));
k = k/10;
}
return sum;
}
public static void main(String args[])
{
System.out.println(findSum(713));
}
}
當我的輸入為 82 時,我的代碼返回 19,因為 1^2 + 9^2 是 82。
但是,我想修改我的代碼,以便我的代碼繼續對每個數字求平方並將它們相加,直到只剩下一個非零數字。
所以基本上,如果我的輸入是 19,代碼將返回 1 ,因為:
1^2 + 9^2 = 82,其中數字 8 和 2 可以:8^2 + 2^2 = 68,其中數字 6^2 + 8^2 = 100,其中 1^2 + 0^ 2 + 0^2 = 1。
我應該對我的代碼進行哪些更改才能使其正常工作?
您可以通過檢查sum > 9
來遞歸調用您的方法
public static int findSum(int k)
{
int sum = 0;
while (k != 0)
{
sum = sum + ((k % 10)*(k % 10));
k = k/10;
}
return sum > 9 ? findSum(sum) : sum;
}
public static boolean check_base10(int k){
String total = String.valueOf(k);
for (int i = 1; i < total.length(); i++) {
if (total.charAt(i) != '0' ) {
return false;
}
}
return true;
}
public static void main(String args[])
{
int result = findSum(713) ;
do { /* rerun the function until the condition of while is verified*/
result = findSum(result) ;
}
while(!check_base10(result)) ; /* check wether number is base 10 */
System.out.println(result);
}
我認為這應該回答你的問題,你重新運行你的 function 直到你的條件在while()
中成功滿足
只有在遇到第一個非零余數后才開始累加:
public static int findSum(int k) {
int sum = 0;
boolean foundNonZero = false:
for (; k != 0; k /= 10) {
if (foundNonZero) {
sum += (k % 10)*(k % 10);
} else {
foundNonZero = k % 10 != 0;
}
}
return sum;
}
請注意用for
替換while
和使用簡潔的算術語法所達到的簡潔性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.