简体   繁体   English

Java:简单递归问题

[英]Java: Simple Recursion Issue

I'm extremely new to the whole idea of recursion, and it's blowing my mind a bit to be honest. 我对递归的整个概念非常陌生,说实话让我有些惊讶。 I'm trying to turn this function I wrote into a recursive one... 我试图将我编写的此功能转换为递归功能...

public static int to_number(String s)
{
    int total = 0;
    int n=s.length();
    for(int i = 0 ; i < n ; i++) { 
        char c = s.charAt(i);
        if (Character.isDigit(c)){
            int value=Character.getNumericValue(c);
            total +=value;
        }
    }
    System.out.println(total);
    return total;
}

It reads in a string, such as "3aaa6a3", iterates through the string, if the char is a digit, it adds it to total, and so on. 它读取一个字符串,例如“ 3aaa6a3”,遍历该字符串,如果char是一个数字,则将其添加到total中,依此类推。 What I have so far... 我到目前为止所拥有的...

    public static int to_number(String s)
{
    int total = 0;
    int n=s.length();
    int i=0;
    if (i == n){
        return 0; //if gone through the whole string
    }
    char c = s.charAt(i);
        if (Character.isDigit(c)){
            int value=Character.getNumericValue(c);
            total +=value;
        }

    System.out.println(total);
    i++;
    to_number(); //trying to call the same function
    return total;
}

I feel like I'm close, but just not getting it. 我觉得我已经接近了,但没有得到。 Thanks for your time and effort! 感谢您的时间和精力!

Not gonna give you the code, but as a recursive function, you want to process the first character of the input string, then call yourself with the remaining string, ie to_number(s.substring(1)) , and combine the result. 不会给您代码,但是作为递归函数,您想处理输入字符串的第一个字符,然后用剩下的字符串(即to_number(s.substring(1))进行调用,然后合并结果。 Recursion ends when input string is empty. 输入字符串为空时,递归结束。

try this 尝试这个

public void intToNum(String s, int total[])
{

     if(s.isEmpty())
        return;

     char c = s.charAt(0);

if (Character.isDigit(c)){
            int value=Character.getNumericValue(c);
            total[0] +=value;
        }

intToNum(s.substring(1),total);

}

and in your main, call the function as 并在您的主体中,将该函数称为

int [] total = new int[1];

intToNum(input,total);

System.out.println(total[0]);

or another approach is 或另一种方法是

public int intToNum(String s) { public int intToNum(String s){

     if(s.isEmpty())
        return 0;

     char c = s.charAt(0);

if (Character.isDigit(c)){

            int value=Character.getNumericValue(c);

            return value + intToNum(s.substring(1));
        }

return intToNum(s.substring(1));

}

This answer contains the solution. 此答案包含解决方案。 Just look at it when you are stuck. 卡住时只看一眼即可。 I also encourage you to read and understand the code instead of just copying it. 我也鼓励您阅读和理解代码,而不仅仅是复制代码。 This is one of the most important concepts in programming, so make sure you understand it and are familiar with it. 这是编程中最重要的概念之一,因此请确保您了解并熟悉它。 :) :)

How it works: The method receives a string. 工作原理:该方法接收一个字符串。 If the string is longer than 1 character, the method splits it in half, calls itself on the two substrings and adds the two results. 如果字符串长于1个字符,则该方法将其分成两半,在两个子字符串上调用自身,并将两个结果相加。 Those calls will do the same thing, until the string fragments are only 1 (or 0) characters long. 这些调用将执行相同的操作,直到字符串片段只有1个(或0个)字符长。 In that case, it just returns their value (or 0, if there is no value). 在这种情况下,它将仅返回其值(如果没有值,则返回0)。

public class RecursionVsIteration {
    public static void main(String[] args) {
        String str = "2.938fyfh0293urhp2398rpod8723uoihr98y";
        System.out.println("Iterative: " + toNumberIterative(str));
        System.out.println("Recursive: " + toNumberRecursive(str));
    }

    public static int toNumberIterative(String s) {
        int total = 0;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                int value = Character.getNumericValue(c);
                total += value;
            }
        }
        return total;
    }

    public static int toNumberRecursive(String s) {
        int n = s.length();
        // termination criteria
        if (n == 0) { // emtpy string
            return 0;
        }
        if (n == 1) { // on character string
            char c = s.charAt(0);
            return Character.isDigit(c) ? Character.getNumericValue(c) : 0;
        }

        // recursive call (split the string in half and call the method on both substrings)
        return toNumberRecursive(s.substring(0, n / 2)) + toNumberRecursive(s.substring(n / 2, n));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM