public class Solution {
public int reverse(int x) {
// Actually, for overflow cases, what we need is a long integer. Or check the result whether it is larger than Integer.MAX_VALUE. I didnt check this case, because test cases should result in a "long" value, while this function needs a int return
if(Math.abs(x) < 10) return x;
boolean negativeFlag = false;
if (x <0) {
negativeFlag = true;
x = -1*x;// one interesting thing is that if I pass Integer.MIN_VALUE in, x = -1 * x is the same value
}
// Solution 1 -- could be considered as "cheating", using String instead.
// String origin = Integer.toString(x);
// StringBuffer sb = new StringBuffer();
// int i = 0;
// while(i < origin.length()){
// sb.append(origin.charAt(i));
// i++;
// }
// sb = sb.reverse();
// int result = Integer.valueOf(sb.toString());
// if (negativeFlag) result*=-1;
// return result;
// Solution 2
long result;
int xCopy = x/10;
int remainder = x%10;
result = remainder ;
while(xCopy >= 10){
remainder = xCopy%10;
xCopy = xCopy/10;
result = result * 10 + remainder;
}
result = result * 10 + xCopy;
if (negativeFlag) result*=-1;
return (int)result;
}
// Both solutions are accepted by LeetCode
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
No comments:
Post a Comment