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

Leetcode -- Day 11

时间:2015-07-19 01:19:17      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

Question 1

Reverse Integer

Reverse digits of an integer.

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

We need to consider a lot of cases of input. One particular example is how to deal with many zeros in the end of that number.

The most direct way is use string or char array to store the int number and then convert it. But I prefer to use the pure math way to do it as cleaner and easier. 

 1 public class Solution {
 2     public int reverse(int x) {
 3         if (x>=0 && x < 10)
 4             return x;
 5         
 6         boolean flag = true;
 7         
 8         if (x < 0){
 9             x = 0-x;
10             flag = false;
11         }
12         
13         double result = 0;
14         
15         while (x > 0){
16             int mod = x % 10;
17             result = result * 10 + mod;
18             x = x / 10;
19         }
20         
21         if (flag)
22             return result > Integer.MAX_VALUE ? 0 : (int)result;
23         else
24             return 0-result < Integer.MIN_VALUE ? 0 : (int)(0-result);
25         
26     }
27 }

 

Leetcode -- Day 11

标签:

原文地址:http://www.cnblogs.com/timoBlog/p/4657921.html

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