Concise java accepted solution,int->String->int

  • 1
    public class Solution {//12:50~1:13
    public int reverse(int x) {
        int flag=x<0 ? -1:1;
        int x2=Math.abs(x);
        String res1=String.valueOf(x2);//int->string
        String res2=new String();
        for(int i=res1.length()-1;i>=0;i--){//reverse the string
        return flag*Integer.parseInt(res2);//string->int
       }catch(NumberFormatException e){//if the reversed number out of range,return 0
           return 0;

    The idea is to convert int into String,reverse the String and change it back into int.The only thing to mention is the "-" symbol and the "numberformatexception".

  • 0

    Almost the same for me was also accepted - I used StringBuilder instead of a String during the process, as res2+=res1.charAt(i); will allocate a new String.

    Do you think, that this solution would be accepted on a real world interview?

  • 0

    omg,can we use catch block?

Log in to reply

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