我為課堂作業(yè)做了這個(gè)方法。計(jì)算任何給定數(shù)字中出現(xiàn)的“1”的數(shù)量。我想對此進(jìn)行擴(kuò)展并學(xué)習(xí)如何取一個(gè)數(shù)字,如果它是偶數(shù)則加一。如果它是奇數(shù),則使用遞歸從其中減去一個(gè)并返回更改后的數(shù)字。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 回答

呼喚遠(yuǎn)方
TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
您經(jīng)常會發(fā)現(xiàn)在遞歸解決方案中使用私有方法會使您的代碼更加清晰。
/**
* 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);
}
添加回答
舉報(bào)
0/150
提交
取消