【发布时间】:2020-04-28 15:43:01
【问题描述】:
我有两种非递归方法,其中一种读取字符串中的总“e”字符,另一种检查 ArrayList 是否按字母顺序排列。
public static int counter( String str ) {
int k = 0;
for( int i = 0; i < str.length(); i++) {
if( str.charAt(i) == 'e' || str.charAt(i) == 'E' ) {
k++;
}
}
return k;
}
public static boolean isAlpha( ArrayList<String> words ) {
int n = 0;
if ( words.isEmpty() ) {
return false;
} else if ( words.size() == 1 ) {
return true;
}
while( n < (words.size() - 1) ){
int j = words.get(n).compareTo( words.get(n + 1));
if ( j > 0 ) {
return false;
}
n++;
}
return true;
}
递归方法的定义是方法调用自身。我相信我理解这个概念,但是很难实现或将其转换为递归方法。我怎样才能把这些方法变成递归的,在做的时候我应该怎么想? 另外,这是我的另一种方法,它只打印出指定数字大小的数字。
public static void printN( int n, int step ) {
if ( step > Math.pow( 10, n - 1 ) - 1 ) {
if ( step < Math.pow( 10, n ) - 1 ) {
if ( step % 2 == 0 ) {
if ( condition( step )) {
System.out.print( step + " " );
}
}
}
}
if ( step >= Math.pow( 10, n ) ) {
return;
}
printN( n, step + 1 );
}
条件方法检查数字的第一个数字(从右边开始)是否大于第二个数字,并再次检查第二个数字是否大于第三个数字。这个检查过程一直持续到最后一位。是否可以仅使用“int n”的参数值编写 printN“方法”?加上只有一个参数值的递归方式的“计数器”方法?
【问题讨论】: