Reverse Integer

Reverse digits of an integer.

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


Solution 1(Trivial)

在Java当中把int转化成string太过于简单, 这样可以很容易得到 x 对应的char[], 然后反转就可以了;

public class Solution {
    public int reverse(int x) {
        /*
        * Step 1: what are the edge cases?
        * x < 0, manipulate on -x
        * x valid but reverse(x) is overflown?
        * x has some 0's, for example 10020, the reverse is 02001?
        */
        boolean isNegative = false;
        if(x < 0){
            x = 0-x;
            isNegative = true;
        }
        
        // step 2: change x into an array:
        // a bad trick
        String s = "" + x;
        char[] chs = s.toCharArray();
        
        // step 3: reverse
        int ans = 0;
        for(int i=chs.length-1; i>=0; i--){
            ans = ans*10 + (chs[i] - '0');
        }
        
        
        return isNegative?0-ans:ans;
        
    }
}

Time complexity is O(n)

Space is O(1), simply because the size of an int is limited to be within 32 in Java


Follow up: 比如在C++当中, 没有这么简单的itoa的函数要如何操作?

Solution 2: 要自己实现一个 itoa的函数

    private int[] itoa(int x){
        // x is guaranteed that x>0
        Deque<Integer> deq = new LinkedList<Integer>();
        while(x >= 0){
            if( x < 10){
                deq.addFirst(x);
                break;
            }else{
                deq.addFirst(x%10);
                x = x/10;
            }
        }
        
        int[] ans = new int[deq.size()];
        for(int i=0; i<ans.length; i++){
            ans[i] = (deq.removeFirst()) ;
        }
        
        return ans;
    }

Note that by going backwards, examples such as "100100" is no longer a special case.


Solution3: Do the problem in-situ. with O(1) extra space;

public class Solution {
    public int reverse(int x) {
        /*
        * Step 1: what are the edge cases?
        * x < 0, manipulate on -x
        * x valid but reverse(x) is overflown?
        * x has some 0's, for example 10020, the reverse is 02001?
        */
        boolean isNegative = false;
        if(x < 0){
            x = 0-x;
            isNegative = true;
        }
        
        //step 2: generate the ans
        int ans = 0;
        while(x >= 0){
            int at = x%10;
            x = x/10;
            ans = ans*10 + at;
            if(x == 0)
                break;
        }
        
        return isNegative?0-ans:ans;
        
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值