# How to handle overflow if I solve this problem using string operations?

• ``````public int reverse(int x) {
boolean porm = true;
if (x<0){
porm = false;
x =-x;
}
String str = Integer.toString(x);
char[] rsvstr = new char[str.length()];
int len = str.length();
for(int i=0;i<str.length();i++){
rsvstr[i] = str.charAt(len-1);
len--;
}

String strstr = new String(rsvstr);
int rvsint = Integer.parseInt(strstr);
if(porm==false){
rvsint = -rvsint;
}
return rvsint;
}
``````

Above is my code, and I don't have any solution to deal with the overflow since I use string to reverse the integer. As in previous discussion, I found the idea to reverse the integer without using string operation. But how about the solution for the string operation to check the overflow?

• If you're handling this problem with strings, here are a few things you can use:

• There's Integer.MAX_VALUE (and Integer.MIN_VALUE)
• Integer.MAX_VALUE is 2147483647 (10 numbers), therefor, Integer.toString(x).length() will never be > 10.
• If Integer.toString(x).length() == 10, then you need to check x's last digit thru the first one to see if the reversed value is > 2147483647

//Overflow check
if (input.length() == 10) {
for (int i=0; i < input.length(); i++) {
if ( input.charAt(input.length() -1 -i) > maxValue.charAt(i))
return 0;
}

After the overflow check the rest of the algorithm is pretty straight forward, as follows:

StringBuffer buffer = new StringBuffer();
for(int i=0; i < input.length(); i++) { buffer.append(input.charAt(input.length()-1-i)); }
return Integer.parseInt(buffer.toString());

Cheers.

• Nice idea that converting the Integer.MAX_VALUE to string and then comparing the length and each digit.
Thanks for help!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.