【问题标题】:Move a number to the left in a string recursive在字符串递归中将数字向左移动
【发布时间】:2020-05-01 08:32:05
【问题描述】:

任务是通过递归将字符串中的数字移动到字符串的开头。字符串中始终只包含一个数字。因此,如果我将“ba3nana”提供给代码,它应该返回“3banana”。已经做了一些递归任务,但我坚持这一点。我试过了,我猜已经有 50 种不同的组合,但到目前为止,我的代码只返回“banana3”,所以我的号码正好相反。我知道这段代码将每个数字都向右移动,但仍然无法找出正确的组合来获得左侧数字的输出。如果我改变一切,一切都会反过来变成“3ananab”

方法的调用如下所示:

System.out.println(shiftDigitLeft("ba3nana"));

这是目前返回banana3的代码:

private static String shiftDigitLeft(String text) {
        if (text.isEmpty()) {
            return text;
        } else {
            if (text.charAt(0) >= '\u0030' && text.charAt(0) <= '\u0039') {
                return shiftDigitLeft(text.substring(1)) + text.charAt(0);
            } else {
                return text.charAt(0) + shiftDigitLeft(text.substring(1));
            }
        }
    }

如果有人能告诉我它是如何正确完成的,将不胜感激,在此先感谢!

【问题讨论】:

    标签: java recursion


    【解决方案1】:

    做同样的事情,但从最后一个字符开始并向后移动:

    private static String shiftDigitLeft(String text) {
        if (text.isEmpty()) {
            return text;
        } else {
            if (text.charAt(text.length() - 1) >= '\u0030' && text.charAt(text.length() - 1) <= '\u0039') {
                return text.charAt(text.length() - 1) + shiftDigitLeft(text.substring(0, text.length() - 1));
            } else {
                return shiftDigitLeft(text.substring(0, text.length() - 1)) + text.charAt(text.length() - 1);
            }
        }
    }
    

    【讨论】:

    • 非常感谢!现在看到它让我明白我做错了什么,但可以肯定的是,我需要更多的时间才能得到这个结果。
    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2014-07-10
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多