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

leetcode----------Reverse Integer

时间:2014-12-18 13:30:17      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   sp   for   

题目 Reverse Integer
通过率 34.2%
难度 Easy

Reverse digits of an integer.

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

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer‘s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    这是一个数字反转的问题,翻转的思想是将原数不断模10取余再除10,从个位按照移位不断得到各个位置的数字,正好是结果从高位到低位的各个位置的数字,对结果的处理正好和原数相反,不断乘10加余数。

   此题目需要注意的几点是:

   1. 首先对原数x按照几个范围进行划分,a.-10<x<10的范围直接返回x; b.其他情况;

   2. 需要设置一个boolean类型变量来标记原数的符号,负数需要转换为正数进行处理,结果再附加上符号;

   3. 注意越界的情况,原数不会出现越界,但是反转以后的数字会存在越界的情况!!!!

java代码:

public class Solution {
    public int reverse(int x) {
        if(x>-10&&x<10) return x;
        boolean flag = x>0?true:false;
        long temp = x;
        long result =0;
        temp = temp>0?temp:-temp;
        while(temp>0)
        {
            result = result*10+temp%10;
            temp /=10;
        }
        if(result>Integer.MAX_VALUE){
            return 0;
        }else if(flag)
        {
            return (int)result;
        }else
        {
            return -(int)result;
        }
    }
}

 

leetcode----------Reverse Integer

标签:style   blog   http   ar   io   color   os   sp   for   

原文地址:http://www.cnblogs.com/pku-min/p/4171452.html

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