zoukankan      html  css  js  c++  java
  • 剑指offer——python【第49题】把字符串转换成整数

    题目描述

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

    示例

    输入

    +2147483647
        1a33

    输出

    2147483647
        0

    题目描述

    因为题目要求不能用库函数,这就很头疼。。然后百度了一下,说是可以把字符串转化为ascii码(的十进制值),对照表http://ascii.911cha.com/,转换函数是ord,也就是返回字符的对应ascii码,而chr则正好和ord相反,把一个整数转换为对应的字符。

    class Solution:
        def StrToInt(self, s):
            res,pos,mult = 0,1,1 ###res是初始返回值;pos是正负标记;mult是位数的乘数,个位是1,十位是10,百位是100
            if not s:#字符串为空
                return res
            elif len(s)==1:#字符串长度为1单独讨论
                if 48 < ord(s) <= 57:
                    return ord(s)-48
                else:
                    return 0
            elif s[0]=='-' or s[0]=='+':#字符串前面有正负号单独讨论
                if s[0]=='-' and s[1]!='0':
                    pos = -1
                    s = s[1:]
                elif s[0]=='-' and s[1]=='0':
                    return res
                elif s[0] =='+' and s[1]!='0':
                    pos = 1
                    s = s[1:]
                elif s[0]=='+' and s[1]=='0':
                    return res
            for i in range(len(s)-1,-1,-1):#对去掉正负号的字符串依次取值
                if '9' >= s[i] >= '0':
                    res += (ord(s[i])-48)*mult
                    mult = mult*10
                else:
                     return 0
            return res*pos
    人生苦短,何不用python
  • 相关阅读:
    Autofac 依赖注入
    C#高级语法
    @helper
    Spiral Matrix -- LeetCode
    Best Time to Buy and Sell Stock with Cooldown -- LeetCode
    Kth Smallest Element in a Sorted Matrix -- LeetCode
    Number of Connected Components in an Undirected Graph -- LeetCode
    Super Ugly Number -- LeetCode
    Ugly Number II -- LeetCode
    Missing Ranges -- LeetCode
  • 原文地址:https://www.cnblogs.com/yqpy/p/9568678.html
Copyright © 2011-2022 走看看