2017-04-17 63 views
-2

我的方法是,例如,如果int [] num123 = {1,2,3};应该输出123。在主要方法。它正在输出零点。在convert num方法中,当我更改最后一个零时,它只是输出它被替换的任何数字。我们不允许使用任何循环,所以这就是我难住的。递归方法问题

public int convertNum(int[] num) { 

    return numHelper(num, 0, num.length - 1, 0); 

} 

private int numHelper(int[] num, int atIndex, int lastIndex, int result) { 

    atIndex = num.length - 1; 
    if (atIndex == lastIndex) { 
     return result; 
    } 

    if (num.length > 0) { 
     atIndex += 1; 

    } 

    return (int) (num[atIndex] * Math.pow(10, lastIndex - atIndex)) 
      + numHelper(num, atIndex + 1, lastIndex, result); 

} 
+4

传递参数'atIndex'的意义是什么,当你做的第一件事是用'atIndex = num.length - 1'代替时,**立即结束递归**? – Andreas

+0

固定。现在它是outoutput 20 –

+0

请澄清您的具体问题或添加额外的细节,以确切地突出你所需要的。正如目前所写,很难确切地说出你在问什么。 –

回答

0

你可能会改变你的递归逻辑。您只能通过nums[]indexresult

private int numHelper(int[] nums, int atIndex, int result) { 
    if (atIndex == nums.length) { 
     return result; 
    } 

    int check = result;     // save previous result 
    result = result * 10 + nums[atIndex]; 

    // result might cycle through Integer.MIN_VALUE after hitting the Integer.MAX_VALUE 
    if(check > result) { 
     throw new NumberFormatException(); 
    } 
    return numHelper(nums, ++atIndex, result); 
} 

呼叫从自己的主类此方法或任何其他方法

public int convertNum(int[] num) { 
    // say, nums = new int[]{1,2,3} 
    return numHelper(num, 0, 0); // atIndex and result are 0 
} 

样品测试
输入:nums = { 1,2,3}输出:123
输入:nums = { 8,9,1,2,3,4,9,3,5,1 }输出:java.lang.NumberFormatException
输入:nums = { 8,9,1,2,3,4,9,3,5,1 }输出:322414759当您评论throw关键字

请注意,由于整数在整个范围内循环,您可能会得到不正确的结果。
注意:请确保您的阵列具有Integer.MAX_VALUE | 2147483647范围内的元素并始终使用throw new NumberFormatException();

+0

非常感谢! –

+0

@ J.Doe,请记住,你总是可以对你发现的答案赞不绝口。我会很感激。谢谢。 –

+0

只是再次感谢。 –