网络编程
位置:首页>> 网络编程>> Python编程>> python如何实现int函数的方法示例

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

作者:熔遁丶螺旋手里剑  发布时间:2022-06-02 08:37:38 

标签:python,int函数

前言

拖了这么久,最终还是战胜了懒惰,打开电脑写了这篇博客,内容也很简单,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

来源:http://www.cnblogs.com/baiyb/p/8452993.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com