7. 整数反转
class Solution {
public:
int reverse(int x) {
int sign = 1;
long long y = x;
if (x < 0)
{
sign = -1;
y = -(long long)x;
}
long long ret = 0;
while (y > 0)
{
ret = (ret * 10) + (y % 10);
y = y / 10;
}
ret *= sign;
return ret < INT_MIN || ret > INT_MAX ? 0 : ret;
}
};
8. 字符串转换整数 (atoi)
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int myAtoi(string str) {
unsigned long len = str.length();
// 去除前导空格
int index = 0;
while (index < len) {
if (str[index] != ' ') {
break;
}
index++;
}
if (index == len) {
return 0;
}
int sign = 1;
// 处理第 1 个非空字符为正负符号,这两个判断需要写在一起
if (str[index] == '+') {
index++;
} else if (str[index] == '-') {
sign = -1;
index++;
}
// 根据题目限制,只能使用 int 类型
int res = 0;
while (index < len) {
char curChar = str[index];
if (curChar < '0' || curChar > '9') {
break;
}
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && (curChar - '0') > INT_MAX % 10)) {
return INT_MAX;
}
if (res < INT_MIN / 10 || (res == INT_MIN / 10 && (curChar - '0') > -(INT_MIN % 10))) {
return INT_MIN;
}
res = res * 10 + sign * (curChar - '0');
index++;
}
return res;
}
};
9. 回文数
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber / 10;
}
};