Reputation: 13
public int reverse(int x) {
String xString=String.valueOf(Math.abs(x));
StringBuffer reverseX=new StringBuffer (xString);
if (x>=Integer.MIN_VALUE & x<=Integer.MAX_VALUE) {
reverseX=reverseX.reverse();
if (x<0)
reverseX=reverseX.insert(0,"-");
return Integer.parseInt(reverseX.toString());
}
else
return 0;
}
Runtime Error Message:
Line 12: java.lang.NumberFormatException: For input string: "9646324351"
Last executed input:
1534236469
What's wrong? help plz Orz!!!
Upvotes: 0
Views: 1730
Reputation: 7947
public long reverse(int x) {
String xString=String.valueOf(Math.abs(x));
StringBuffer reverseX=new StringBuffer (xString);
if (x>=Integer.MIN_VALUE & x<=Integer.MAX_VALUE) {
reverseX=reverseX.reverse();
if (x<0)
reverseX=reverseX.insert(0,"-");
return Long.parseLong(reverseX.toString());
}
else
return 0L;
}
You can try above code.
As this 9646324351
value is out of range of int type.You need to provide larger datatype for this String to numeric conversion.
As we know
double's range > long's range >int's range
Also you can try BigInteger
Hope this will help you.
Upvotes: 0
Reputation: 69450
if you try to call your method with the value:
reverse(9646324351);
You get an Compiler error, which leads you to the Problem:
The literal 9646324351 of type int is out of range
So i do not understand why you can get an error in your method.
Use a long/Long or a BigInterger in your program
Here you can rad about the data types and which range they cover
Upvotes: 1
Reputation: 3612
Use biginteger class instead of Integer Read the docs https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
Upvotes: 0
Reputation: 45319
That number is too large to be parsed as an Interger, it exceeds Integer.MAX_VALUE
.
Rather use Long.parseLong
Upvotes: 1