[英]finding the largest digit in an integer using recursion
我有一个练习,他的任务是使用 java 中的递归找到 integer 中的最大数字。 例如,对于数字 13441,将返回数字“4”。
我已经尝试了一天,但没有任何效果。
我认为可以工作的是以下代码,我无法完全了解以下代码:
public static int maxDigit(int n) {
int max;
if (n/100==0) {
if (n%10>(n/10)%10) {
max=n%10;
}
else
max=(n/10)%10;
}
else if (n%10>n%100)
max=n%10;
else
max=n%100;
return maxDigit(n/10);
}
如您所见,这是完全错误的。
任何帮助都会很棒。 谢谢
这通过递归比较最右边的数字与其余数字的最高数字(通过将原始数字除以10得到的数字)来工作:
int maxDigit(int n) {
n = Math.abs(n); // make sure n is positive
if (n > 0) {
int digit = n % 10;
int max = maxDigit(n / 10);
return Math.max(digit, max);
} else {
return 0;
}
}
最简单的基本情况是,如果n为0,则返回0。
public static int maxDigit(int n){
if(n==0) // Base case: if n==0, return 0
return 0;
return Math.max(n%10, maxDigit(n/10)); // Return max of current digit and
// maxDigit of the rest
}
或者,更简洁一些;
public static int maxDigit(int n){
return n==0 ? 0 : Math.max(n%10, maxDigit(n/10));
}
我不会深入研究您的代码,我认为它比必须的要复杂。 但是在我看来,情况实际上很简单(除非我遗漏了一些东西):
基本情况:参数只有一位,返回该位作为参数
一般情况:返回(参数中的第一个数字)和(参数中剩余的数字的maxDigit中的较高者)
您也可以写:
public static int maxDigit(int n, int max){
if(n!=0) {
if(n%10 > max) {
max = n%10;
}
return maxDigit(n/10, max);
}
return max;
}
这就是解决方案。
public static int maxDigit(int n, int max){
if (n!=0){
if ( n%10 > max){
max = n%10;
return maxDigit(n/10,max);
}else{
return maxDigit(n/10,max);
}
}
return max;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.