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;
}
}