gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:07:41 25 4
gpt4 key购买 nike

前言

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

问题

正如所暗示的,我想仅使用递归和条件来重新创建加法运算符。尽管我完成了大部分代码,但仍然存在一个问题,因为我包含了一个加法运算符。这是代码(运行良好,并按预期添加正、负和零输入的所有变化)。我还添加了一些平庸的评论作为帮助。

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);但似乎它无法摆脱递归,并且确实抛出了该网站的标题,a 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);
}

可耻地取自here 。所有功劳都归功于其作者。

关于 java |仅使用递归和条件创建显式加法函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34340598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com