首页 > 代码库 > LeetCode:Reverse Integer

LeetCode:Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
      Example2: x = -123, return –321

这道题应该不用详细说了。比较简单。唯一的是要注意特殊值0.


public class Solution {
     public int reverse(int x) {
        StringBuilder sb = new StringBuilder();
        if(x==0)return x;
        else if(x<0)
        {
            sb.append(‘-‘);
        }
        x = Math.abs(x);
        while(x != 0)
        {
            sb.append(x%10);
            x = x/10;
        }
        String result = sb.toString();
        return Integer.parseInt(result);
    }
}