LeetCode--Reverse Integer

Reverse digits of an integer.

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

思路:

  很简单的思路,对x对10取余数,把x从低位到高位的数字依次提取出来,再每次对结果乘10加上新取出的个位,最后x=x/10,循环到x为0为止。

public class Solution {
    public int reverse(int x) {
        int result = 0;
        while(x!=0){
            result = result*10+x%10;
            x /=10;
        }
        return result;
        
    }
}

 Spoiler:

  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?

  Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

  spoiler指出了要考虑溢出的情况,32位有符号整数的取值范围是-2147483648~2147483647,一共2^32次方个,从新写了个带判断溢出的结果,判断依据是正数加正数如果为负数了则是溢出,负数加负数为正数了也是溢出。

package com.bupt.tools;
import java.util.Scanner;
public class Test {
    
    private static boolean flag;
    
    public static int reverseint(int x){
        flag = false;
        int sign=x>0?1:-1;
        int result = 0;
        while(x!=0){
            result = result*10+x%10;
            x/=10;
        }
        if(sign==1){
            if(result<0){
                flag = true;
                return -1;
            }
        }
        else if(sign==-1){
            if(result>0){
                flag = true;
                return -1;
            }        
        }
        return result;
    }
    
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        while(sc.hasNext()){
            int result = Test.reverseint(sc.nextInt());
            if(!Test.flag)
                System.out.println(result);
            else
                System.out.println("Overflow!");
         }
        sc.close();
        
    }

}

 

posted @ 2014-10-21 23:29  buptzjf  阅读(133)  评论(0编辑  收藏  举报