首页 > 其他 > 详细

Leetcode -- Day 11

时间:2015-07-19 01:17:31      阅读:238      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!