剑指Offer 49. 把字符串转换成整数 (字符串)

Posted on 2018-10-17 16:39  _hqc  阅读(139)  评论(0编辑  收藏  举报

题目描述

将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

输入描述:

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

输出描述:

如果是合法的数值表达则返回该数字,否则返回0

示例1

输入

+2147483647
    1a33

输出

2147483647
    0
题目地址
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tqId=11202&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
思路

思路1: 使用了ord函数

考虑首位是否有符号位

遍历字符串,如果字符串为字母,跳出循环

字符0对应的ASCII码为48,对于每个字符,求其ASCII-48

思路2:使用hash将'0'~'9'和数字0~9映射,再遍历

Python

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        if not s:
            return 0
        sign = 1
        if s[0] == '+' or s[0] == '-':
            if s[0] == '-':
                sign = -1
            s = s[1:]
        # 思路1
        # res = 0
        # for x in s:
        #     if x > '9' or x < '0':
        #         return 0
        #     res = res * 10 + ord(x)- 48
        # return res * sign
        # 思路2:
        dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
        res = 0
        for x in s:
            if x > '9' or x < '0':
                return 0
            res = res * 10 + dict[x]
        return res * sign
if __name__ == '__main__':
    result = Solution().StrToInt('-123')
    print(result)