Java | 仅使用递归和条件创建显式加法函数

前言

通过在我的日程安排中找到一些空闲时间,我对自己提出了提高递归技能的问题(不幸的是)。 作为实践,我想通过使用递归来重新创建所有运算符,第一个是添加。 虽然我有点卡住了。

如上所述,我想通过仅使用递归和条件来重新创建加法运算符。 虽然我完成了很多代码,但仍然存在一个问题,因为我包含了一个加法运算符。 这是代码(运行正常,并在正,负和零输入的所有变体中按预期添加)。 我还包括一些平庸的评论作为帮助。

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  -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–),也不包括按位。 尝试并回答我在自己的实现中遇到的具体问题。

 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); } 

羞耻地从这里取走。 所有功劳都归功于作者。

 public static int add (int a, int b) { if (b == 0) return a; if (b > a) return add (b, a); add (++a, --b); } 

只是用++ / – 。