15.1 Reverse Integer

来源:互联网 发布:淘宝买高压气瓶犯法吗 编辑:程序博客网 时间:2024/06/05 15:47

Link: https://oj.leetcode.com/problems/reverse-integer/

This is easy, I passed OJ after some small revisions.

Time: O(logn), Space: O(1)

My 1st attempt:

public class Solution {    public int reverse(int x) {        if(x == 0) return 0;        int result = 0;        int y = Math.abs(x);        while(y > 0){            result = result * 10 + y%10;            y = y /10;        }        result = x >= 0? result : (-1)*result;        return result;    }}

Note: to get abs of x is unnecessary. The below code is enough:

public class Solution {    public int reverse(int x) {        int result = 0;while(x!= 0){result = result*10 + x%10;x = x/10;}return result;    }}
But to deal with overflow, the code should be like this:

public class Solution {    public int reverse(int x) {        boolean isPositive = x > 0 ? true : false;        int result = 0;        x = Math.abs(x);        while(x > 0){            result = result * 10 + x%10;            x = x /10;        }        if(result < 0) return -1;//deal with overflow        if(!isPositive){            result *=-1;        }        return result;    }}



0 0