leetcode-8-字符串转换整数 (atoi)(中等)

8. 字符串转换整数 (atoi)(中等)

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。

函数 myAtoi(string s) 的算法如下:

  • 读入字符串并丢弃无用的前导空格
  • 检查下一个字符(假设还未到字符末尾)为正还是负号,读取该字符(如果有)。 确定最终结果是负数还是正数。 如果两者都不存在,则假定结果为正。
  • 读入下一个字符,直到到达下一个非数字字符或到达输入的结尾。字符串的其余部分将被忽略。
  • 将前面步骤读入的这些数字转换为整数(即,“123” -> 123, “0032” -> 32)。如果没有读入数字,则整数为 0 。必要时更改符号(从步骤 2 开始)。
  • 如果整数数超过 32 位有符号整数范围 [−2^31, 2^31 − 1] ,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −231 的整数应该被固定为 −231 ,大于 231 − 1 的整数应该被固定为 231 − 1
  • 返回整数作为最终结果

思路:按照上述介绍流程写即可,注意当s中的数字长度很长时的情况,注意只有符号没有数字和只有数字没有符号的情况,最好将数字和符号分开存。

1.C++

class Solution {
public:
    int myAtoi(string s) {
        int n = s.size();
        int i=0,mark=1;
        string temp="";
        long long int res=0;
        while(s[i]==' '){
            i++;
        }
        if(s[i]=='-'){
            mark = -1;
            i++;
        }
        else if(s[i]=='+'){
            mark = 1;
            i++;
        }
        while( s[i]=='0' ){
            i++;
        }
        while( isdigit(s[i])){
            temp+=s[i];
            i++;
        }
        if(temp.empty())
            return 0;
        if(temp.size()>10){
            if(mark==1)
                return 2147483647;
            else
                return -2147483648;
        }
        else{
            res = stoll(temp);
            if (mark*res < -1*pow(2,31))
                return -2147483648;
            if (mark*res > pow(2,31)-1)
                return 2147483647;
            return int(mark*res);
        }

    }
};
  1. python
class Solution:
    def myAtoi(self, s: str) -> int:
        s=s.strip()
        n = len(s)
        mark = 1
        temp = ''
        if n==0:
            return 0
        if s[0]=="-":
            mark = -1
            s= s[1:]
        elif s[0]=="+":
            mark = 1
            s= s[1:]
        i = 0
        while(i<len(s) and s[i]==0):
            i+=1
        while(i<len(s) and s[i].isdigit()):
            temp+=s[i]
            i+=1
        if(len(temp)==0):
            return 0
        else:
            res = mark*(int(temp))
            if res > 2147483647:
                return  2147483647
            elif res <  -2147483648:
                return  -2147483648
            else:
                return int(res)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值