9. Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
代码如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int temp = x;
int t = 0;
long long sum = 0;
while(x)
{
t = x%10;
sum = 10*sum + t;
x = x/10;
}
if(sum<INT_MIN||sum>INT_MAX)
return false;
return sum == temp;
}
};
7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
class Solution {
public:
int reverse(int x) {
int n = 0;
long long sum = 0;
while(x)
{
n = x%10;
sum = 10*sum + n;
x = x/10;
}
if(sum<INT_MIN||sum>INT_MAX)
{
sum = sum>0 ? INT_MAX:INT_MIN;
return 0;
}
return sum;
}
};
8. String to Integer (atoi)
Implement atoi to convert a string to an integer.
class Solution {
public:
int myAtoi(string str) {
int flag = 1;
int i = 0,n = str.size();
if(n<=0)
return 0;
while(i<n&&str[i]==' ')
{
i++;
}
if(str[i]=='+')
{
i++;
}
else if(str[i]=='-')
{
flag = -1;
i++;
}
long long sum = 0;
while(i<n)
{
if(str[i]>='0'&&str[i]<='9')
sum = 10*sum + str[i] - '0';
else
return (int)(flag*sum);
if(sum>INT_MAX||sum<INT_MIN)
return flag>0 ? INT_MAX:INT_MIN;
i++;
}
return (int)(flag*sum);
}
};