java 中加法递归_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 <

*/

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值