前言
通过在日程安排中找到一些空闲时间,我要求自己提高自己的递归技能(不幸的是)。作为实践,我想通过使用递归来重新创建所有运算符,第一个是加法运算。虽然我有点卡住。
题
隐含地,我想仅通过使用递归和条件来重新创建加法运算符。尽管我完成了很大一部分代码,但由于只包含一个加法运算符,仍然存在一个问题。这是代码(可以正常运行,并且可以按预期在正,负和零输入的所有变体中添加)。我还提供了一些平庸的评论作为帮助。
public class Test {
public static void main(String[] args) {
// Numbers to add
int firstNumb = -5, secondNumb = 3;
// Call the add function and save the result
int result = add(firstNumb, secondNumb);
// Print result
System.out.println(result);
}
/*
* Function recursively takes a number from 'giver' one at a time and
* "gives"/"adds" it to 'receiver'. Once nothing more to "give" (second == 0),
* then return the number that received the value, 'receiver'.
*/
public static int add(int receiver, int giver) {
/*
* Base Case since nothing more to add on. != to handle signed numbers
* instead of using > or <
*/
if (giver != 0) {
/*
* Recursive Call.
*
* The new 'giver' param is the incremental value of the number
* towards 0. Ex: -5 -> -4 , 5 -> 4 (so I guess it may decrement).
*
* The new 'receiver' param is the incremental value based on the
* opposite direction the 'giver' incremented (as to why the
* directionalIncrement() function needs both values to determine
* direction.
*/
return add(directionalIncrement(receiver, giver),
directionalIncrement(giver, -giver));
} else {
// Return 'receiver' which now contains all values from 'giver'
return receiver;
}
}
// Increments (or decrements) the 'number' based on the sign of the 'direction'
public static int directionalIncrement(int number, int direction) {
// Get incremental value (1 or -1) by dividing 'direction' by absolute
// value of 'direction'
int incrementalValue = direction / abs(direction);
// Increment (or decrement I guess)
return number + incrementalValue;
}
// Calculates absolute value of a number
public static int abs(int number) {
// If number is positive, return number, else make it positive by multiplying by -1 then return
number = (number > 0.0F) ? number : -number;
return number;
}
}
问题是包含的行return number +
incrementalValue;。如前所述,尽管不符合我自己不涉及任何加法运算符的规范,但代码可与此一起使用。
我将该行更改为,return add(number,
incrementalValue);但似乎无法打破递归规则,的确抛出了该网站的标题,StackOverflowException.
所有帮助表示赞赏。提前致谢。
注意
约束不包含任何隐式的增减(i ++ / i–),也不包含按位。尝试并回答我在自己的实现中遇到的特定问题。