我有x = 10和y = 6的值。 然后,我有这个addxy函数来计算两个数字的总和。 我在这个添加中尽我所能,现在我正在研究如何构建它以获得产品.... 我已经把我的大脑震撼了一天,但我仍然无法得到它......
public static int addxy(int a, int b)
{
if (b==0)
return a;
else
if (b>0)
return 1 + addxy(a,b-1);
else
if (a==0)
return b;
else
return 1 + addxy(a-1,b);
}
任何帮助将不胜感激
答案 0 :(得分:3)
我想你想要这样的东西,对吧?
public static int multiply(int a, int b)
{
if (a == 0 || b == 0)
return 0;
if (a < 0)
return -multiply(-a, b);
if (b < 0)
return -multiply(a, -b);
return multiply(a, b - 1) + a;
}
答案 1 :(得分:2)
如果您想拥有x*y
,那么您必须递归添加x
,y times
,如下所示:
public class Sample {
public static void main(String[] args) {
System.out.println(add(5, 6));
System.out.println(add(-5, 6));
System.out.println(add(5, -6));
System.out.println(add(-5, -6));
}
static int add(int x, int y) {
if (x==0 ||y == 0) {
return 0;
}
if (y > 0)
return x + add(x, y - 1); //for positive numbers
else
return -x + add(x, y + 1); // for negative numbers
}
}
O / P:
30
-30
-30
30
答案 2 :(得分:0)
public static int mulxy( int a, int b ) {
if ( b == 0 || a == 0 ) {
return 0;
}
// We need to solve the sign problem.
int signA = ( a > 0) ? 1 : -1;
int signB = ( b > 0 )? 1 : -1;
// now we know the sign of result.
int signResult = signA * signB;
// we don't need sign anymore
int posA = a * signA;
int posB = b * signB;
return signResult * mulPosAB( posA, posB );
}
public int multPosAB( int a, int b ) {
// here we already know that a and b not -tive.
if( a == 0 || b == 0 ) return 0;
// return a + mulPosAB( a, b - 1 );
// or using newAddXY
return newAddXY( a, mulPosAB( a, b - 1 ) );
}
对于a和b均为负数的情况,您的addxy
也不会工作。
public int newAddXY( int a, int b ) {
if( b == 0 ) return a;
if( a == 0 ) return b;
// We need to solve the sign problem.
int signA = ( a > 0) ? 1 : -1;
int signB = ( b > 0 )? 1 : -1;
//return signB + newAddXY( a, b - signB );
// I think we should ensure we re not adding numbers bigger than 1.
// so this will be better
return newAddXY( signB, newADDXY( a, b-signB ) );
}