题目1:Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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).
思路:
int -2147483648~2147483647
如果输入时是 2147483645,那么,妥妥的倒置后溢出,所以要进行判断,我解决的方法是为防止溢出,先转化为Long,然后和int最大值,最小值比较,如果不满足,返回0;
如果输入是0,输出直接处理为0;
如果输入是负数,倒置前要记录符号。
代码一:转化成string类型
// 与剑指offer上的一道题很相似,要考虑溢出
public class Solution {
public int reverse(int x) {
if(x == 0)
return x;
String num = String.valueOf(x);
int inx = 0;
boolean minus = false;
if(num.charAt(0) == '-'){
minus = true;
inx++;
}
long res = 0;
for(int i = num.length() - 1; i >= inx ; i--){
int flag = minus ? -1 : 1;
res = res * 10 + flag * (num.charAt(i) - '0');
if(isOverflow(res))
return 0;
}
return (int) res;
}
public boolean isOverflow(long x){
if(x > 0){
if(x > 0x7fffffff)
return true;
}
else{
if(x < 0x80000000)
return true;
}
return false;
}
}
代码2:
int reverse(int x) {
//如果溢出,则直接返回0
if(x==0) return x;
int flag=1;//表示正数
if(x<0)
flag=-1;//负数
long res=0;
x=abs(x);//取绝对值
while(x!=0)
{
res=res*10+flag*(x%10);
//判断是否溢出
if(isflow(res))//0代表溢出
return 0;
x/=10;
}
return res;
}
bool isflow(long x)//1代表溢出
{
if(x>0)
{
if(x>INT_MAX)
return true;
}
else
{
if(x<INT_MIN)
return true;
}
return false;
}
题目2:palindrome-number
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.
思路:
判断一个整数是不是回文,并且要求不能使用额外的空间。
方法:迭代的对最高位和最低位,进行比较,一旦发现一个不相等就返回false
取一个整数的最低位可以使用x%10
取一个整数的最高位需要知道最高是哪一位 个、百、千 ····
判断一个整数的最高位是哪一位:
int hi=1;
while(x/hi>=10)
hi*=10;
从而最高位为x/hi
去掉最高位和最低位后: x=(x%hi)/10 , hi=hi/100
所以:
while(x!=0)
{
int left = x/hi;
int right = x%10;
if(left!=right)
return false;
x=(x%hi)/10;
hi=hi/100;
}
//负数不是回文
代码如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x==INT_MIN)
return false;
if(x<0)
return false;
int hi=1;
while(x/hi>=10)
hi*=10;
while(x!=0)
{
int left=x/hi;
int right=x%10;
if(left!=right)
return false;
x=(x%hi)/10;
hi=hi/100;
}
return true;
}