首页 > 试题广场 >

把字符串转换成整数

[编程题]把字符串转换成整数
  • 热度指数:507858 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为 0 或者字符串不是一个合法的数值则返回 0

数据范围:字符串长度满足
进阶:空间复杂度 ,时间复杂度

注意:
①字符串中可能出现任意符号,出现除 +/- 以外符号时直接输出 0
②字符串中可能出现 +/- 且仅可能出现在字符串首位。

输入描述:
输入一个字符串,包括数字字母符号,可以为空


输出描述:
如果是合法的数值表达则返回该数字,否则返回0
示例1

输入

"+2147483647"

输出

2147483647
示例2

输入

"1a33"

输出

0
class Solution:
    def StrToInt(self, s):
        # write code here
        dict_int={
            '0':0,
            '1':1,
            '2':2,
            '3':3,
            '4':4,
            '5':5,
            '6':6,
            '7':7,
            '8':8,
            '9':9,
        }
        count = 1
        resut = 0
        ss='+'
        for i in s:
            if i=="+" and count==1:
                ss='+'
                continue
            if i=="-" and count==1:
                ss="-"
                continue
            if i in dict_int:
                resut =resut*10+dict_int[i]
            else:
                return 0
        if ss=="+":
            return resut
        else:
            return -resut
发表于 2021-05-08 16:26:01 回复(0)
Python 用字典对应,幸好没有四则运算表达式,否则就要做一个计算器了。
只有三种可能:
1. 全数字
2. 有字母
3. 有+或-,在s[0]
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        char2int = {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}
        pos = 0
        res = 0
        for i in range(len(s)-1,-1,-1):
            if s[i].isdigit():
                num = char2int.get(s[i])
                res += num*pow(10,pos)
                pos += 1
            if s[i].isalpha():
                return 0
            if s[i]=="-":
                res = 0-res
        return res
        


发表于 2021-04-17 22:27:19 回复(0)
弱弱的问下能用自带的函数int吗
class Solution:
    def StrToInt(self, s):
        # write code here
        s=s.strip()
        try:
            int(s)
        except Exception as e:
            return 0
        else:
            return int(s)

发表于 2021-04-08 14:38:04 回复(0)

python解法:

# -*- coding:utf-8 -*-
'''
解法1:直接做呗,注意字符转换成整数的方法,可以用s[i]-'0',也可以直接用字典做,比较方便;
这里用字典做;
'''
class Solution:
    def StrToInt(self, s):
        if len(s) == 0:
            return 0
        sign = 1
        res = 0
        # num = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9};
        # 利用字典方便字符转换成数字;
        num = {str(i):i for i in range(10)}
        # 判断首字符是否为正负号;
        if s[0] == '-':
            sign = -1
        # 若是,则从字符串第二位开始判断;
        if s[0] == '-' or s[0] == '+':
            s = s[1:]
        # 计算数值
        for i in s:
            if i not in num:
                return 0
            else:
                # 用num[i]可以直接把字符转换为整数;
                res = res * 10 + num[i]
        return sign*res
编辑于 2021-02-19 17:18:46 回复(0)
import re
class Solution:
    def StrToInt(self, s):
        # write code here
        s=s.replace(' ','')
        pattern=r'^[-+]?\d+$'
        result=re.match(pattern,s)
        if not result:
            return 0
        else:
            return int(result.group())
发表于 2021-02-07 21:43:14 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        if s == "":
            return 0
        nums = [str(i) for i in range(10)]
        nums_map = {str(i):i for i in range(10)}
        s = list(s)
        if s[0] != '+' and s[0] !='-' and s[0] not in nums:
            return 0
        sign = -1 if s[0]=='-' else 1
        if s[0] == '+'&nbs***bsp;s[0] =='-':
            s.pop(0)
        res = 0
        for i in range(0,len(s)):
            if s[i] not in nums:
                return 0
            res += nums_map[s[i]] * 10 ** (len(s)-1-i)
        print(res)
        return res*sign


发表于 2020-12-10 22:24:40 回复(0)
首先判断是不是空,然后判断第一个位置是不是为+-(0-9),如果是,继续判断后面的位置是不是全是数字,如果是,返回 int(s)。 如果后面的位置出现任意一个不是数字的玩意。就跳出循环。返回0
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        
        # write code here
        flag = False
        if len(s) == 0:
            flag = False
            return 0
        if len(s) == 1 and s[0] in ['+','-']:
            flag = False
            return 0
        if s[0] == '+'&nbs***bsp;s[0] == '-'&nbs***bsp;s[0] in ['0','1','2','3','4','5','6','7','8','9']:
            flag = True
        if flag:
            for i in range(1,len(s)):
                if s[i] in ['0','1','2','3','4','5','6','7','8','9']:
                    flag = True
                else:
                    flag = False
                    break
        if flag:
            return int(s)
        if not flag:
            return 0

发表于 2020-09-21 02:13:00 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        try:
            k = int(s)
        except:
            k = 0
        return k

一个不符合题意的python解法
想了半天如何在遵循规则的前提用python解决,想来想去都很不舒服,转念一想,我都用python了还纠结这干啥,就这吧
发表于 2020-09-18 12:56:55 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        try:
            return int(s)
        except Exception :
            return 0
            

发表于 2020-07-30 09:56:29 回复(0)
if not s:return 0
        l = ['0','1','2','3','4','5','6','7','8','9','+','-']
        if s[0] in l and s[1:].isdigit():return int(s)
        else:return 0

发表于 2020-06-29 16:01:55 回复(0)

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        dict_s_dig = {
            '0':0,
            '1':1,
            '2':2,
            '3':3,
            '4':4,
            '5':5,
            '6':6,
            '7':7,
            '8':8,
            '9':9,
            '+':'+',
            '-':'-'
        }
        str_to_dig = 0   #存放转换后的结果
        label = 1        #正负标记
        tmp = 1          #判断+ -出现的位置
        for i,v in enumerate(s):
            if v in dict_s_dig:
                if v != '+' and v != '-':
                    str_to_dig = str_to_dig * 10 + dict_s_dig[v]
                elif v == '-' and i == 0:
                    label = -1
                elif i!= 0 and (v == '+'&nbs***bsp;v == '-'):
                    return 0
            else:
                return 0
        return str_to_dig * label

发表于 2020-06-16 16:18:16 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        dict1={}
        list1=[str(i) for i in range(10) ]
        
        for i in range(10):
            dict1[str(i)]=int(i)
            
        s=list(s)
        lens=len(s)
        if lens==0:
            return 0
        if lens==1:
            if s[0] in list1:
                return dict1[s[0]]
            else:
                return 0
        if s[0]=='+':
            ss=s[1:]
            num=0
            for i in range(len(ss)):
                if ss[i] in list1:
                    num=num+dict1[ss[i]]*(10**(len(ss)-i-1))
                else:
                    return 0
                        
            return num
        if s[0]=='-':
            ss=s[1:]
            num=0
            for i in range(len(ss)):
                if ss[i] in list1:
                    num=num+dict1[ss[i]]*(10**(len(ss)-i-1))
                else:
                    return 0
            return 0-num
        if s[0] in list1:
            ss=s
            num=0
            for i in range(len(ss)):
                if ss[i] in list1:
                    num=num+dict1[ss[i]]*(10**(len(ss)-i-1))
                else:
                    return 0
            return num
        else:
            return 0
                    
                    
            
                
                
        
        # write code here

发表于 2020-05-27 21:18:41 回复(0)
Python解法
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        try:
            ans=int(s)
            if -2**31<=ans<=2**31-1:
                return ans
            else:
                return 0
        except:
            return 0

编辑于 2020-04-04 17:06:09 回复(0)
对于Python来说是相当坑爹的题目。。。
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        (3347)# write code here
        if not s.strip():
            return 0
        sym = ['0', '1', '2','3','4','5','6','7','8','9']
        st = 0
        res = 0
        label = 1
        if s[0] == '+':
            st = 1
        elif s[0] == '-':
            label = -1
            st = 1
        for i in range(st, len(s)):
            c = s[i]
            if c not in sym:
                return 0
            res = res*10+sym.index(c)
        res = label*res
        if -2147483648<=res < 2147483648:
            return res
        return 0

发表于 2020-03-22 23:35:22 回复(0)

正则表达式 提供一个思路

# -*- coding:utf-8 -*-
import re
class Solution:
    def StrToInt(self, s):
        (1264)# write code here
        s=s.lstrip()
        pattern=re.compile(r'[+-]?\d+\b')
        m=pattern.match(s)
        // match方法:尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
        if not m : return 0
        m=int(m.group())
        // group返回匹配成功的整个子串,但是这里还是用到了int()。用findall代替match可以避免用到int()
        if m>(1<<31)-1 or m<-(1<<31):return 0
        //判断是否溢出
        return m
  • [+-]:代表一个+字符或-字符
  • ?: 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
  • \d:一个数字
  • +:匹配前面一个字符的一个或多个
  • \b: 匹配一个单词边界,例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
编辑于 2020-03-03 17:49:53 回复(0)
# -*- coding:utf-8 -*-
# 加入了边界判断
class Solution:
    def StrToInt(self, s):
        numList = ['0','1','2','3','4','5','6','7','8','9']
        intNum = 0
        label = 1 # 正负标志位
        if s == "":
            return 0
        # 判断首位
        if s[0] == "+":
            label = 1
            s = s[1:]
        elif s[0] == "-":
            label = -1
            s = s[1:]
        else:
            pass # 占位符
        for i in s:
            if i in numList:
                intNum = intNum*10 + numList.index(i)
            if i not in numList:
                intNum = 0
                break
            # 边界判断
            if label == 1 and intNum > 0x7FFFFFFF:
                intNum = 0
                break
            if label == -1 and intNum > 0x80000000:
                intNum = 0
                break
        return intNum*label

发表于 2020-02-17 17:05:08 回复(0)
# -*- coding:utf-8 -*-
# 解题思路:1.判断符号位; 2.遍历各位判断字符是否是合法的数字字符
# 3.计算结果 4.判断越界 5.处理负数
class Solution:
    def StrToInt(self, s):
        # write code here
        if not s:
            return 0

        minus = False
        index = 0
        res = 0
        if s[0] == '+':
            index += 1

        if s[0] == '-':
            minus = True
            index += 1

        for i in range(index, len(s)):
            if '0' <= s[i] <= '9':
                res = res * 10 + (ord(s[i]) - ord('0'))
            else:
                return 0

        # c 语言Int有符号数的最大正值,超出越界
        if not minus and res > pow(2, 31) - 1:
            return 0

        # c 语言Int有符号数的最小负值,超出越界
        if minus and res > pow(2, 31):
            return 0

        if minus:
            res = 0 - res

        return res

发表于 2020-01-20 10:19:06 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        l = ['0','1','2','3','4','5','6','7','8','9','+','-']
        if s == "":
            return 0
        else:
            if s[0] in l and s[1:].isdigit() == True:
                if s[0] == '+':
                    return int(s[1:])
                else:
                    return int(s)
            else:
                return 0
请问大家这个为什么不对啊
发表于 2020-01-14 17:22:28 回复(0)