遇到将字符串转换为 Int 的递归问题

所以问题如下。您将创建一个将字符串作为参数的方法,该字符串由所有数字组成,您需要将该字符串转换为整数。您必须使用递归解决方案来解决问题。


我编写了以下代码,当我输入“1234”或“138775”时它工作得很好,但是一旦我输入一个包含 0 的数字,它就会返回一个奇怪的结果。


100、1001、101 和 12045 分别返回 10、11、110 和 1245。如上所述,当我向它发送诸如“1234”或“14384”之类的东西时,代码工作得很好,但是一旦有零,它就会倾向于删除该零。


我已经尝试了不同的 int 到 Integer 类的字符串转换,例如 parse(int) 但结果相同。


/**

 * converts a string of numbers to an int

 * 

 * @param String str: original string of numbers

 * @return int recursiveStringInt: returns the int value of the string

 */

public static int recursiveStringInt(String str)

{

    if(str.length() == 1)

        return Integer.valueOf(str);

    else

    {

        return Integer.valueOf(str.substring(0,1) + recursiveStringInt(str.substring(1)));

    }

}

谢谢你们的帮助!


如果需要澄清,请告诉我。


www说
浏览 253回答 3
3回答

不负相思意

你的括号有点偏离你想要做的事情,逻辑需要一些工作..你想要的是获取当前字符串的最后一个字符,将其转换为整数,并将其添加到字符串的前面乘以 10。int recursiveStringInt(String str) {    int length = str.length()    if(length == 1)        return Integer.valueOf(str);    else    {        int temp = Integer.valueOf(str.substring(length-1)) + ( 10 * recursiveStringInt(str.substring(0,length-1)));        return temp;    }}“8”的小情况导致仅执行第一个块。“83”的下一个情况导致 temp = 3 + (10 * 8) = 83“103”的下一种情况导致 temp = 3 + (10 * (0 + (10 * 1))) = 103

HUX布斯

这是因为当你解析一个像054int这样的子字符串时,它会变成54.试试这个代码:-public static int recursiveStringInt(String str) {    return str.length() == 1            ? Integer.valueOf(str)            : (int) (Integer.parseInt(str.substring(0, 1)) * Math.pow(10, str.length() - 1)) + recursiveStringInt(str.substring(1));}我用过这个逻辑:-105 = 1*100 + 0*10 + 5*1编辑:如果你不理解三元运算符,这里是 if-else 版本:-public static int recursiveStringInt(String str) {    if (str.length() == 1) {        return Integer.valueOf(str);    } else {        return (int) (Integer.parseInt(str.substring(0, 1)) * Math.pow(10, str.length() - 1)) + recursiveStringInt(str.substring(1));    }}

倚天杖

尝试使用分压解决方案public static void main(String[] args) {&nbsp; &nbsp; System.out.println(recursiveStringInt("12034", 0));}public static int recursiveStringInt(String str, int pow){&nbsp; &nbsp; if(str.length() < 1)&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int temp = Integer.valueOf(str.substring(str.length() -1))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* (int) Math.pow(10.0, 1.0 * pow);&nbsp; &nbsp; &nbsp; &nbsp; temp += recursiveStringInt(str.substring(0, str.length() -1), pow + 1);&nbsp; &nbsp; &nbsp; &nbsp; return temp;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java