1.题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
2.思路:
这个问题一开始自己拿到手的时候就觉得需要考虑的条件好多啊,又有溢出问题考虑,又有正负绝对值判断,又有10的反转是1这种判断;然后没有具体的思路,查看了别人优秀的代码之后,发现对整数边界条件考虑的非常巧妙;
“这种问题的考察重点并不在于问题本身,越是简单的题目越要注意细节,一般来说整数的处理问题两点:符号和整数越界问题”
1)溢出:在数据相加后,如果超过最大位数产生溢出的时候,系统会将超过最大位数的高位二进制数扔掉,从而导致计算结果不一样;
2)正负:不需要判断,计算过程中 不影响。
3)10反转后为1:如果10取余之后是0,相加自然为0
主要思路:
1)直接用while循环====
3.代码:
public class Solution {
public int reverse(int x) {
//翻转int 需要考虑数组溢出等问题 以及整10的后面需要
int res = 0;
while(x != 0){
int tail = x%10;
int newRes = res*10+tail;
if((newRes - tail)/10 != res){
return 0;
}
res = newRes;
x = x/10;
}
return res;
}
}
上面这个题目有一个扩展:
1.判断一个int数字是否是回文数,首先,负数不能是回文数;
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
2.这里主要是根据上面一个题目做修改,反转整数后判断他们是否相等,可以不用考虑溢出问题,还有注意负数判断;
3.代码:
public class Solution {
public boolean isPalindrome(int x) {
//判断一个数x是否是回文数--直接逆转一个整数即可
int res = 0;
if(x<0){
return false;
}
int tmp = x;
while(x != 0){
int tail = x%10;
int newRes = res*10+tail;
res = newRes;
x = x/10;
}
if(res == tmp){
return true;
}else{
return false;
}
}
}
代码简化:
public class Solution {
public boolean isPalindrome(int x) {
//判断一个数x是否是回文数--直接逆转一个整数即可
int res = 0;
if(x<0){
return false;
}
int tmp = x;
while(x != 0){
res= res*10+x%10;
x = x/10;
}
return res == tmp;
}
}