The code given below works fine for two digit numbers, that is, up to 99 but i dont know why it breaks after that. for eg. it gives 51 as output for number 123 but it should be 321. can anyone help me in this?
public class Main
{
static int reverse(int n){
if(n<10)
return n;
else
return ((n)*10) (reverse(n/=10));
}
public static void main(String[] args) {
System.out.println(reverse(123));
}
}
CodePudding user response:
You're doing math addition, use string concatenation that'll be easier
static String reverse(int n) {
if (n < 10)
return "" n;
else
return "" n % 10 reverse(n / 10);
}
CodePudding user response:
For n
123: n % 10 * 10
yields 30. Next you are dividing by 10, getting 12, which you pass in your recursive call. Since your method works correctly for 2 digit numbers, you correctly get 21. 30 21 equals 51.
A recursive method using only math (as opposed to for example string manipulation) is not that simple. I think I would resort to an iterative solution. If you want to use this problem for training recursion, you should probably look into string manipulation as already suggested by azro.
To illustrate the challenge with combining math and recursion think of how you would reverse 102. Expecting 201. There are two ways:
- Either you pass 10 to a recursive call and a append the result to 2. The reverse of 10 is 01, which you will get as 1, so the naive solution will give you 21, not 201. There probably is a way to know that the intermediate result from the recursive call should be understood as two digits, you would need to be creative.
- Or you pass 02 to a recursive call and append 1 to the result. Again the naive way of doing it would yield 21, not 201.
CodePudding user response:
You zero out the last digit only in reverse. This only works for numbers less than 100 (with a single recursive call).
CodePudding user response:
The problem is with the ((n)*10)
. This part should concatenate the last digit with the reversed number, but it only multiplies the digit by ten and sum it. For numbers with two digits, it works, as multiplying by 10 is essentially putting the number in the second position in the first position. But it won't work for numbers larger than that.
You should concatenate strings instead.