很水的两道题目
1.Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
就是把一个int类型的数倒着输出
所以这里面存在着溢出的可能性 我们可以使用long long去存储这个数 最后判断是否溢出
-2147483648~2147483647(int的范围)
代码如下:
class Solution {
public:
int reverse(int x) {
queue<int>q;
bool flag=true;
int a,b;
long long sum=0;
if(x<0)flag=false;
x=abs(x);
while(x)
{
a=x%10;
x=x/10;
q.push(a);
}
while(!q.empty())
{
b=q.front();
q.pop();
sum=b+sum*10;
}
if(!flag)sum=-sum;
if(sum<INT_MIN||sum>INT_MAX)return 0;
return sum;
}
};
2.判断int是否是回文的
Determine whether an integer is a palindrome. Do this without extra space.
注意:不能使用多余的空间,所以我们不能开辟一个string类型 我们可以用刚刚那道题的做法 把一个数倒序 然后判断它和原来是否相等
代码如下:
class Solution {
public:
bool isPalindrome(int x) {
long long sum=0;
int y=x;
if(y<0)return false;
while(x)
{
sum=sum*10+x%10;
x=x/10;
}
if(y==sum)return true;
else return false;
}
};
这就这两道简单题的解法