Search code examples
javaruntime-errorreverseparseint

trying to return integer in reverse (without recursion)


i'm trying to print the reverse of a given integer. the function must take in an integer and return an integer (w/o recursion or printing each number as a string individually). this is what I've got but it's not working:

class Solution {
public int reverse(int x) 
{
    String numStr = "";
    while (x > 0)
    {  
        numStr = numStr + Integer.toString(x % 10);
        x /= 10;
    }
    return Integer.parseInt(numStr);
}
}

i'm getting a runtime error for my return statement. Any help or advice is greatly appreciated!


Solution

  • You don't need a String here, just accumulate each digit and multiply the current value by 10 (to shift right). Also, your method can be static. Like,

    public static int reverse(int x) {
        int r = 0;
        while (x > 0) {
            r = (r * 10) + (x % 10);
            x /= 10;
        }
        return r;
    }