问题
Here is my function that suppose to reverse and return giver integer:
public static int reverse(int x) {
List<Integer> digits = new ArrayList<>();
int result = 0, count = 0;
while(x != 0) {
digits.add(x % 10);
x /= 10;
count++;
}
System.out.println(digits);
int i = 0;
while(count != 0) {
result += digits.get(i) * (int) Math.pow(10, count - 1);
System.out.printf("result: %d i: %d, count: %d - ", result, i, count);
System.out.printf("%d * %d\n", digits.get(i), (int) Math.pow(10, count - 1));
count--;
i++;
}
return result;
}
I encountered a problem. For example when I pass value of 1534236469 this is what happens:
result: 410065408 i: 0, count: 10 - 9 * 1000000000
.
.
.
1056389759
Why this is happening? Also all tips on making this function better are welcome.
回答1:
Also all tips on making this function better are welcome.
A simple implementation can be as follows:
public class Main {
public static void main(String[] args) {
int x = 123456789;
int y = reverse(x);
System.out.println(x);
System.out.println(y);
}
public static int reverse(int x) {
return Integer.parseInt(new StringBuilder(String.valueOf(x)).reverse().toString());
}
}
Output:
123456789
987654321
Also, as already mentioned in the comment, when you assign a value bigger than the maximum allowed value to an int
variable, the value gets converted into a value from the other end i.e. Integer.MAX_VALUE + 1
becomes Integer.MIN_VALUE
. Therefore, for an integer like 1534236469
whose reverse is bigger than an int
variable can hold, you should convert the reverse into a long
value as shown below:
public class Main {
public static void main(String[] args) {
int x = 1534236469;
long y = reverse(x);
System.out.println(x);
System.out.println(y);
}
public static long reverse(int x) {
return Long.parseLong(new StringBuilder(String.valueOf(x)).reverse().toString());
}
}
Output:
1534236469
9646324351
回答2:
Marcin, you can implement your reverse method like below,
public static long reverse(int x) {
long reverseDigit = 0;
while (x != 0) {
reverseDigit = reverseDigit * 10 + (x % 10);
x /= 10;
}
return reverseDigit;
}
I hope this helps.
回答3:
A more proper way to reverse an integer would be:
int reverse(int n) {
int reversed = 0;
Boolean isNegative = n < 0;
n = Math.abs(n);
while(n > 0) {
reversed = reversed * 10 + (n % 10);
n /= 10;
}
if (isNegative)
reversed *= -1;
return reversed;
}
回答4:
I think the problem could be, that the reverse of an int ist not always an int.
2147483647 is max int so,
9646324351
is too big and 1534236469 has no chance
来源:https://stackoverflow.com/questions/62488531/why-my-calculations-are-wrong-java-reverse-int-problem