我為課堂作業做了這個方法。計算任何給定數字中出現的“1”的數量。我想對此進行擴展并學習如何取一個數字,如果它是偶數則加一。如果它是奇數,則使用遞歸從其中減去一個并返回更改后的數字。public static int countOnes(int n){ if(n < 0){ return countOnes(n*-1); } if(n == 0){ return 0; } if(n%10 == 1){ return 1 + countOnes(n/10); }else return countOnes(n/10);}0 將 = 1 27 將 = 36 依此類推。我將不勝感激所提供的任何幫助。
1 回答

呼喚遠方
TA貢獻1856條經驗 獲得超11個贊
您經常會發現在遞歸解決方案中使用私有方法會使您的代碼更加清晰。
/**
* Twiddles one digit.
*/
private static int twiddleDigit(int n) {
return (n & 1) == 1 ? n - 1 : n + 1;
}
/**
* Adds one to digits that are even, subtracts one from digits that are odd.
*/
public static int twiddleDigits(int n) {
if (n < 10) return twiddleDigit(n);
return twiddleDigits(n / 10) * 10 + twiddleDigit(n % 10);
}
添加回答
舉報
0/150
提交
取消