leedcode做题总结,题目Reverse Integer----- 2011/12/25

这个题是要求把1234变成4321,我的方法是用数字依次取余10的不同次方,剥离掉每一位打入栈,同时从源数中减去直到减为0为止。

之后出栈依次乘以10的不同次方加起来就行了

发现自己的问题有,Math.parw(a,b)可以求a^b,但是返回的是double,需要用(int)x将其转回


public int reverse(int x) {
        int x2=Math.abs(x);
        int y=0;
        int ji=1;
        Stack<Integer> s = new Stack<Integer>();
        while(x2!=0){
            int tmp=(int)(x2%(Math.pow(10,ji)));
            x2=x2-tmp;
            tmp = (int)(tmp/Math.pow(10,ji-1));
            s.push(tmp);
            ji++;
        }
        ji=0;
        while(!s.isEmpty()){
            y=y+(int)(s.pop()*Math.pow(10,ji));
            ji++;
        }
        if(x>=0)return y;
        else return -y;
    }

Update 2015/08/19: 上面的方法完全不忍直视,这道题完全不需要用栈,只要在求原数每一位的时候同时生成新的数即可。leetcode新加了test case, 转换后的新数有可能大于int范围,所以需要判断是否大于int范围,而且要注意这道题不需要检查正负,因为负数求余还是负数, 比如-123 % 10 = -3

public class Solution {
    /**
     * @param n the integer to be reversed
     * @return the reversed integer
     */
    public int reverseInteger(int n) {
        // Write your code here
        long res = 0;
        while (n != 0){
            res = res * 10 + n % 10;
            n = n / 10;
        }
        if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE)
                return 0;
        return (int)res;
        
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值