Share my simple java solution


  • -3
    X
    public class Solution {
        public int reverse(int x) {
            StringBuffer buffer=new StringBuffer(Integer.toString(Math.abs(x)));
            buffer.reverse();
            if(x<0) buffer.insert(0,"-");
            
            try{
            return Integer.parseInt(buffer.toString());
            }catch( NumberFormatException e){
                return 0;
            }
        }
    }

  • 0
    T

    So I just learnt about String buffers. I used Strings to do this, including a standalone reverseString method. Thank you for sharing your elegant solution.

    Just one question: Is there any advantage to using Integer.toString() over String.valueOf()?


  • 0
    X

    I think there is no big difference between Integer.toString() and String.valueOf(). You can use any one.


Log in to reply
 

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