当前位置:主页 > 软件编程 > Python代码 >

python如何实现int函数的方法示例

时间:2021-05-28 07:59:45 | 栏目:Python代码 | 点击:

前言

拖了这么久,最终还是战胜了懒惰,打开电脑写了这篇博客,内容也很简单,python实现字符串转整型的int方法

python已经实现了int方法,我们为什么还要再写一遍,直接用不就好了?事实确实如此,但是int函数看似简单,实际上自己来实现还是有一些坑的

1.判断正负

这点很容易忘记

2.python不能字符串减法

python不能像c++一样直接使用s - '0'直接实现个位数的字符串转整型,而是需要转换ascii码,ord(s) - ord('0')来实现转换

3.判断是否超限

这也是手写int函数最容易忽略的问题,返回结果不能出int的限制,python中int类型的最大值使用sys.maxint查看。但是python语言很神奇,实际上python内置的int方法并没有结果必须小于maxint的限制

下面给出我的python实现

#!/use/bin/env python
# _*_ coding:utf-8 _*_
import sys
max_int = sys.maxint
num_tuple = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
def _int(input_string):
 total_num = 0
 is_minus = False
 string = input_string.strip()
 if string.startswith('-'):
  is_minus = True
  string = string[1:]
 for s in string:
  if s not in num_tuple:
   print "input error"
   return 0
  num = ord(s) - ord('0')
  total_num = total_num * 10 + num
  if total_num > max_int:
   total_num = max_int
   break
 return total_num * -1 if is_minus else total_num

总结

您可能感兴趣的文章:

相关文章