I want to reverse an int but it doesn't work. For example, 123 should return 321, but the printed number is 356.
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123, 0));
}
static int reverse2(int a, int i) {
if(a == 0) {
return 0;
} else {
i = i*10 a%10;
System.out.println(i);
return i = reverse2(a/10, i);
}
}
}
CodePudding user response:
You are greatly complicating your recursive function for printing an integer in reverse. For one, there is no good reason for reverse2
to have two integer arguments, as you can achieve your desired results with a single argument. The trick is to access the rightmost digit with the % 10
operation then shift that digit off the number with the / 10
operation. Consider these revisions:
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123));
}
static String reverse2(int number) {
if(number == 0) {
return "";
} else {
return number % 10 reverse2(number / 10);
}
}
}
CodePudding user response:
Your code should look like this:
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123, 0));
}
static int reverse2(int a, int i) {
if(a == 0) {
return i;
} else {
i = i*10 a%10;
System.out.println(i);
return reverse2(a/10, i);
}
}
}
You should return i
when a is 0
.
You shouldn't add i
when you call the reverse2
function because you're adding i
twice.
CodePudding user response:
You can do it like this. You only need to pass the value you are reversing. The math computation computes 10 to the power of the number of digits in the argument.
public static int reverse(int v) {
int reversed = 0;
if (v > 0) {
int d = (int)Math.pow(10,(int)(Math.log10(v)));
reversed = reverse(v%d) * 10 v/d;
}
return reversed;
}