【剑指Offer】49把字符串转换成整数

题目描述

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

时间限制:1秒;空间限制:32768K;本题知识点:字符串

解题思路

本题利用ASCII码来求解,要充分考虑各种情况,如输入为空、输入首字符为+/-号,输入只有+/-号等。

Python代码:

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        result = 0
        sign = 1
        if not s:
            return 0
        if ord(s[0]) == ord('+'): #第一个字符是+号
            s=s[1:]
            sign = 1
            if len(s)==0: #只有一个+号
                return 0
        if ord(s[0]) == ord('-'): #第一个字符是-号
            s=s[1:]
            sign = 0
            if len(s)==0: #只有一个-号
                return 0
        for i in range(len(s)):
            if ord(s[i])>=ord('0') and ord(s[i])<=ord('9'):
                result += ord(s[i])-ord('0')
            else:
                return 0
            result *= 10
        result /= 10
        return result if sign else -result

 

posted @ 2018-10-30 16:48  yucen  阅读(112)  评论(0编辑  收藏  举报