You have one problem on line 1 of your Bik Method:
Every time you call it the variable sum
is defined to 0
so it never changes. Also in your code you never actually sum the value from the previous iteration. The solution I can come with is to pass another parameter with the sum of the previous iteration:
public static int Bik (int n, int sum) {
// You get the value of the last digit and sum it to your total
sum += n%10;
// This validation is to know if there is only 1 digit left
if (n>9)
// The required recursion
return Bik(n/10, sum);
//In case the sum is higher than 9 the recursion is called again, otherwise it returns the sum
return sum>9 ? Bik(sum, 0) : sum;
}
public static void main(String[] args) {
System.out.println(Bik(1892, 0));
}
Please note this solution also works for numbers in which the recursion has to run more than once like 189235. Also I used a ternary operator. You can learn more about it here but if you don’t like it you can use a regular if
statement as well
2
solved Java – Recursive solving with check number [closed]