gpt4 book ai didi

java - 我应该如何递归地编写这个Java函数?

转载 作者:行者123 更新时间:2023-11-30 02:36:07 26 4
gpt4 key购买 nike

我正在尝试递归地编写下面的 Java 代码:

public static int count(String word) {
int numValue = 0;
int length = word.length();
for(int i=0; i<length; i++){
String alpha = "abcdefghijklmnopqrstuvwxyz";
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
}
return numValue;
}


public static void main(String[] args) {
System.out.println(count("abc"));
}

该函数返回输入字符串参数中每个字母的索引之和。

我正在尝试递归地编写相同的代码,有人能指出我哪里出了问题吗?

public static int count(int numValue, int i, String word) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
if( i >= word.length()){
return numValue;
}
else{
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
count(numValue, i=i+1, word);
}
return numValue;
}

public static void main(String[] args) {
System.out.println(count(0,0, "abc"));
}

最佳答案

更简单的方法是一次又一次地缩小字符串。

public static int count(String word) {
if (word.isEmpty()) {
return 0;
}
final String alpha = "abcdefghijklmnopqrstuvwxyz";
return alpha.indexOf(word.charAt(0)) + count(word.substring(1));
}

关于java - 我应该如何递归地编写这个Java函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43030817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com