# "如何判断字符串是否是整数"（python）

class Test:
def __init__(self):
self.flag = None

def getFlag(self):
return self.flag

# 判断c是否是数字，如果是返回数字，且设置flag=True,否则返回False
def isNumber(self, c):
return c >= '0' and c <= '9'

# 判断str是否是数字
def strtoint(self, strs, length):
if length > 1:
if not self.isNumber(list(strs)[length - 1]):
# 不是数字
print("不是数字")
self.flag = False
return -1

if list(strs)[0] == '-':
return self.strtoint(strs, length - 1) * 10 - (ord(list[length - 1]) - ord('0'))
else:
return self.strtoint(strs, length - 1) * 10 + ord(list(strs)[length - 1]) - ord('0')

else:
if list(strs)[0] == '-':
return 0
else:
if not self.isNumber(list(strs)[0]):
print("不是数字")
self.flag = False
return -1
return ord(list(strs)[0]) - ord('0')

def strToint(self, s):
self.flag = True
if s == None or len(s) <= 0 or (list(s)[0] == '-' and len(s) == 1):
print("不是数字")
self.flag = False
return -1

if list(s)[0] == '+':
return self.strToint(s[1:len(s)], len(s) - 1)
else:
return self.strToint(s, len(s))

class Test:
def __init__(self):
self.flag = None

def getFlag(self):
return self.flag

# 判断c是否是数字，如果是返回True,否则返回False
def isNumber(self, c):
return c >= "0" and c <= "9"

def strToint(self, strs):
if strs == None:
self.flag = False
print("不是数字")
return -1
self.flag = True

res = 0
i = 0
minus = False  # 是否是负数

if list(strs)[i] == '-':  # 结果是负数
minus = True
i += 1

if list(strs)[i] == '+':  # 结果是正数
i += 1
while i < len(strs):
if self.isNumber(list(strs)[i]):
res = res * 10 + ord(list(strs)[i]) - ord('0')
else:
self.flag = False
print("不是数字")
return -1
i += 1
return -res if minus else res

if __name__ == "__main__":
t = Test()
s = "-543"
print(t.strToint(s))
s = "543"
print(t.strToint(s))
s = "+543"
print(t.strToint(s))
s = "++43"
result = t.strToint(s)
if t.getFlag():
print(result)


08-28 6894
06-06 1万+
01-24 1656
10-22 2万+