Recursion java - Testing is the sum of the two Integers are equal Boolean function -
i have write recursive function accepts 2 integers. function returns true if first number digit amount equal second number, otherwise function returns false.
the function return true.
what doing wrong?
the code:
public static boolean amountequal(int num1, int num2) { int sum1 = 0, sum2 = 0; if (num1 == 0 && num2 == 0 && sum1 == sum2) return true; else if (num1 == 0 && num2 == 0 && sum1 != sum2) return false; sum1 += num1 % 10; sum2 += num2 % 10; return amountequal(num1 / 10, num2 / 10); }
thank's
what doing wrong?
you using sum
zero. need figure out way pass sum1
, sum2
along, final invocation make decision based on prior invocations.
one way of doing making recursive function 4 parameters, , adding two-parameter overload start recursive chain:
public static boolean amountequal(int num1, int num2) { return amountequal(num1, num2, 0, 0); } private static boolean amountequal(int num1, int num2, int sum1, int sum2) { ... // recursive code goes here }
another approach compute digit differential, i.e. sum of digits in num1
minus sum of digits in num2
, , return true
if differential zero:
public static boolean amountequal(int num1, int num2) { return digitdifferential(num1, num2) == 0; } private static int digitdifferential(int num1, int num2) { return (num1 != 0 || num2 != 0) ? num1%10 - num2%10 + digitdifferential(num1/10, num2/10) : 0; }
Comments
Post a Comment