zoukankan      html  css  js  c++  java
  • 将字符串转换成整数

    题目描述

    将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

    输入描述:

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

    输出描述:

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

    Python代码1:

     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     def StrToInt(self, s):
     4         # write code here
     5         if len(s)==0:
     6             return 0
     7         end = len(s)-1
     8         begin = -1
     9         temp = 1
    10         int_s = 0
    11         if s[0]=='-' or s[0]=='+':
    12             begin = 0
    13         for i in range(end,begin,-1):
    14             if s[i]<'0' or s[i]>'9':
    15                 return 0
    16             int_s += temp*int(s[i])
    17             temp = temp *10
    18         if s[0]=='-':
    19             int_s = -int_s
    20         return int_s

    Python代码2

    使用列表,当成大数处理,牛客一直通不过,最终还是得将字符串改为整数,很纳闷

     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     # 大数问题
     4     def StrToInt(self, s):
     5         # write code here
     6         if len(s) == 0:
     7             return 0
     8         if len(s)==1 and (s[0]<'0' or s[0]>'9'):
     9             return 0
    10         end = len(s) - 1
    11         begin = -1
    12         int_s = [0]*len(s)
    13         if s[0] == '-' or s[0] == '+':
    14             begin = 0
    15         for i in range(end, begin, -1): #range()函数,左闭右开 
    16             if s[i]>='0' and s[i]<='9':
    17                 int_s[i] = s[i]
    18             else:
    19                 return 0
    20         if s[0] == '-':
    21             int_s[0] = '-'
    22         if s[0]=='+':
    23             int_s = int_s[1:]
    24         return int(''.join(int_s))


  • 相关阅读:
    Vue常见问题总结
    vue学习记录
    内卷
    at least once 和 at most once 问题
    IO学习笔记(全)
    IO学习笔记7
    IO学习笔记6
    IO学习笔记5
    IO学习笔记4
    IO学习笔记3
  • 原文地址:https://www.cnblogs.com/shuangcao/p/12849782.html
Copyright © 2011-2022 走看看