前言
通过在我的日程安排中找到一些空闲时间,我不得不自我提高我的递归技能(不幸的是)。作为实践,我想通过使用递归来重新创建所有运算符,第一个是添加。虽然我有点卡住了。
问题
如上所述,我想通过仅使用递归和条件来重新创建加法运算符。虽然我完成了很多代码,但仍然存在一个问题,因为我包含了一个加法运算符。这是代码(运行正常,并在正,负和零输入的所有变体中按预期添加)。我还将一些平庸的评论作为帮助。
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--),也不包括按位。尝试并回答我在自己的实现中遇到的具体问题。
答案 0 :(得分:1)
public static int add(int a, int b) {
if(b == 0) return a;
int sum = a ^ b; //SUM of two integer is A XOR B
int carry = (a & b) << 1; //CARRY of two integer is A AND B
return add(sum, carry);
}
羞辱地从here获取。所有功劳都归功于作者。
答案 1 :(得分:1)
public static int add (int a, int b) {
if (b == 0) return a;
if (b > a) return add (b, a);
add (++a, --b);
}
用++ / - 。