💒把字符串转换成整数
🧸读题
字符串转整形,遇到不是 +
-
的其他字符直接返回0;
而这里的+
-
是正负数的意思,正数要省略+
,负数要显示-
。
🧸代码
我的思路是,管他正负,直接转,遇到其他字符返回0
当是结果要求是正数
,就直接输出。
如果是负数
,就用的得到的正数减去2倍
的自己
class Solution {
public:
bool isNumber(char ch)
{
if(ch >= '0' && ch<= '9')
{
return true;
}
else if( ch == '+' || ch =='-')
{
return true;
}
return false;
}
int StrToInt(string str) {
//'1' - '0' = 1
int end = str.size()-1;
int ret = 1;//计算位数
int count = 0;//计数
while(0 <= end)
{
while(0 <= end && !isNumber(str[end]))
{
return 0;
}
if(str[end] != '+'&& str[end]!='-')
{
count += (str[end] - '0')*ret;
ret*=10;
}
--end;
}
if(str[0] == '-')
{
count -= 2*count;
}
return count;
}
};
🧸解读代码
class Solution {
public:
是一个判断 数字的函数 是数字/+/-返回true,否则返回false
bool isNumber(char ch)
{
if(ch >= '0' && ch<= '9')
{
return true;
}
else if( ch == '+' || ch =='-')
{
return true;
}
return false;
}
int StrToInt(string str) {
//'1' - '0' = 1
从尾部开始计算
int end = str.size()-1;
int ret = 1;//计算位数
int count = 0;//计数
end从后向前遍历,end小于0时 则停止,等于0 说明还有一个字符,也要进去
while(0 <= end)
{
判断是不是其他字符,是其他字符直接返回0
while(0 <= end && !isNumber(str[end]))
{
return 0;
}
走到这就不是其他字符 要么是数字,要么是+-
判断不是+- 就进去
if(str[end] != '+'&& str[end]!='-')
{
来到这里,ret初始值一定是1
因为是0的话 就一直输出0
count += (str[end] - '0')*ret;
各位是最后一位,所以最后一位*1还是各位
第二次要*10 所以这里ret*=10
ret*=10;
}
算玩一位,end要向前走
--end;
}
这里判断负数,如果第一位是 - 则减去2倍的自己
if(str[0] == '-')
{
count -= 2*count;
}
return count;
}
};