LeetCode第八题--字符串转整数

在这里插入图片描述

C++

字符型数字减去字符‘0’就能得到对应的数字形式

class Solution {
public:
    int myAtoi(string s) {
        unsigned long len = s.length();
        int index=0;
        while(index<len){
            if(s[index]!=' ') break;
            index++;
            if(index==len) return 0;
        }
        int sign=1;
        int res=0;
        if(s[index]=='+') index++;
        else if(s[index]=='-'){
            index++;
            sign = -1;
        }
        while(index<len){
            char c = s[index];
            if(c<'0'||c>'9') break;
            if(res>INT_MAX/10||(res==INT_MAX/10)&&((c-'0')>INT_MAX%10)) return INT_MAX;
            if(res<INT_MIN/10||(res==INT_MIN/10)&&((c-'0')>-(INT_MIN%10))) return INT_MIN;
            res = res*10 + sign*(c - '0');
            index++;
        }
        return res;

    }
};

Python

class Solution:
    def myAtoi(self, s: str) -> int:
        index, res, sign = 0, 0, 1
        while index<len(s) and s[index]==' ':
            index=index+1
        if len(s)==0 or index==len(s):
            return 0
        if s[index]=='-':
            sign=-1
        if s[index]=='+' or s[index]=='-':
            index=index+1
        while index<len(s) and '0'<= s[index]<='9':
            c = int(s[index])
            res = res*10 + c*sign
            index+=1
            if res<= -2**31:  return -2**31
            elif res >= 2**31-1: return 2**31-1
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值