这个题是要求把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;
}
}