7. Reverse Integer(反转整型) —— Java

来源:互联网 发布:奥米姿淘宝 编辑:程序博客网 时间:2024/06/07 13:05

Reverse digits of an integer.

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


Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

class Solution {    public int reverse(int x) {        if(x<10 && x>-10)            return x;        int max = Integer.MAX_VALUE;        int min = Integer.MIN_VALUE;        long verse = 0;        int remainder = x % 10;        int sign = 0;        if(x<=-10){            x = -x;            sign = 1;        }        while(x > 0){            remainder = x % 10;            verse = verse * 10 + remainder;                     x = x / 10;        }        if(verse > max || verse < min)            return 0;        if(sign == 1)            return -(int)verse;        else            return (int)verse;    }}




阅读全文
0 0