码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Integer

时间:2017-11-05 10:51:28      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:length   nbsp   long   math   hold   sed   --   environ   blog   

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

 

Example 2:

Input: -123
Output: -321

 

Example 3:

Input: 120
Output: 21

 

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

没啥难度

    public int reverse(int x) {
        boolean p = true;
        if(x<0) { p = false;x=-x;}
        long res=0;int i = Integer.toString(x).length()-1;
        while(x>0) {
              res+=(x%10)*Math.pow(10, i--);
              if(res>Integer.MAX_VALUE) return 0;
              x=x/10;
        }
        return p?(int)res:-(int)res;
    }

 

Reverse Integer

标签:length   nbsp   long   math   hold   sed   --   environ   blog   

原文地址:http://www.cnblogs.com/swuwyb/p/7786768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!