8.字符串转整数
这道题想了挺久的,暴力求解。参考了其他人的求解方法
c++:0ms 8.6MB
class Solution {
public:
int myAtoi(string str) {
int num = 0;
int flag = 1;//正数
int n = str.size();
int i = 0;
int ax = INT_MAX / 10;
int mo = INT_MAX % 10;
while(str[i] == ' ' && i < n)
{
i++;
}
if(str[i] == '+')
{
if(str[i+1] < '0' || str[i] > '9')
{
return 0;
}
i++;
}
if(str[i] == '-')
{
if(str[i+1] < '0' || str[i+1] > '9')
{
return 0;
}
flag = -1;
i++;
}
for(; str[i] >= '0' && str[i] <= '9' && i < n; i++)
{
// 越界处理
if(num > ax || (num == ax && (str[i]-'0') > mo))
{
return flag == -1?INT_MIN:INT_MAX;
}
num = num*10+(str[i]-'0');
}
return num*flag;
}
};
看到一个大神用stringstream来读取数字,牛的一批,咱还费那劲。。。
c++:0ms 8.4MB
while(*str.begin() == ' ') str.erase(str.begin());
if(str == "") return 0;
stringstream ss;
ss<<str;
int n;
ss>>n;
return n;
python:看人家用一行正则表达直接解决,优秀。
class Solution:
def myAtoi(self, str: str) -> int:
return max(min(int(*re.findall('^[\+\-]?\d+', str.lstrip())), 2**31 - 1), -2**31)
str.lstrip():去除字符串前面的空格,返回处理后的字符串,
^:字符串匹配
[+-]:代表开头为一个’+'或’-’字符
?:前面一个字符可有可无
\d:一个数字
+:前面一个字符的一个或多个
\D:一个非数字字符
*:签一一个字符的0个或多个
2.确定输入的整数是否为回文
c++:我这里定义变量为long而不是int,因为怕出现溢出的错误,16ms,7.9MB
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)// 小于0直接不为回文
{
return false;
}
long temp = x;
long temp1 = 0;
long temp3 = 0;
while(temp>0)
{
temp1 = (temp3 + temp1)*10;
temp3 = temp % 10;
temp = temp/10;
}
temp1 += temp3;
if(temp1 == x)
{
return true;
}
else
{
return false;
}
}
};
有个大神用了三种方法,优秀啊。
方法一:转成字符串
class Solution {
public:
bool isPalindrome(int x) {
string tmp=to_string(x);
string tmp2=tmp;
reverse(tmp2.begin(),tmp2.end());
if(tmp==tmp2) return true;
return false;
}
};
方法二:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
if(x/10==0) return true;
vector<int> tmp;
while(x>0){
tmp.emplace_back(x%10);
x=x/10;
}
for(int i=tmp.size()-1,j=0;i>0,j<i;i--,j++)
if(tmp[i]!=tmp[j]) return false;
return true;
}
};
方法三:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
if(x/10==0) return true;
long long cur = 0;
int num = x;
while(num != 0) {
cur = cur * 10 + num % 10;
num /= 10;
}
return cur == x;
}
};