字符串转float强转float(str)
手动实现一个转换函数:

'''
input type:str() eg:'314.545'
output type:int()eg : 314.545
'''
import math def myAtoi(str):str = str.strip()print("str",str)sign = 1num = 0float_num = 0if not str:return 0if str[0] == "+":str = str[1:]elif str[0] == "-":sign = -1str = str[1:]#integer partfor ch in str:if ch == '.':break      if ch >= "0" and ch <= "9":num = num * 10 + ord(ch) - ord('0')#fractional partfor ch in reversed(str):if ch >= "0" and ch <= "9":       float_num =   (ord(ch) - ord('0')) + float_num*0.1# print("float_num",float_num)if ch == '.':float_num = 0.1*float_numbreaknum = num +float_numnum = num * signreturn num
str_name="-531.124445"
b = myAtoi(str_name)# you can test it with the following code
# print(type(myAtoi(str_name)))
# print(b)

此题源于LeetCode第8题

Implement atoi which converts a string to an integer.The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.If no valid conversion could be performed, a zero value is returned.Note:Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:Input: "42"
Output: 42
Example 2:Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.Then take as many numerical digits as possible, which gets 42.
Example 3:Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.Thefore INT_MIN (−231) is returned.
class Solution(object):def myAtoi(self, str):""":type str: str:rtype: int"""if str.strip() != "":ss = ""flag1 = 0flag = 0str1 = str.strip()for i in str1:if not i.strip().isalpha():if i.strip().isdigit():ss = ss + iflag = 1elif i == "-" or i == "+":if flag==1:breakss = ss + ielse:breakelse:breakprint(ss)for f in range(len(ss) - 1):if ss[0] == "0":ss = ss[1:]flag1 = 1if flag1 == 1:if not ss.isdigit():return 0if ss == "-":return 0if ss == "":print("zeli")return 0elif ss.startswith("-"):if ss[1:].isdigit():dd = int(ss[1:])if dd > 2 ** 31:print("-1**31")return -2 ** 31else:print("-dd")return -ddelse:return 0elif ss.startswith("+"):if ss[1:].isdigit():cc = int(ss[1:])if cc > 2 ** 31-1:print("2**31")return 2 ** 31-1else:print("cc")return ccelse:return 0else:if ss.isdigit():cc = int(ss)if cc > 2 ** 31-1:print("2**31")return 2 ** 31-1else:print("cc")return ccelse:return 0else:return 0Solution().myAtoi("  42")
Solution().myAtoi("  -42")
Solution().myAtoi("  +42")
Solution().myAtoi("12ds")
Solution().myAtoi("-0012d12")
print("========")
Solution().myAtoi("dsfs12")
Solution().myAtoi("3.14")
Solution().myAtoi("-91283472332")
Solution().myAtoi("91283472332")
Solution().myAtoi("")
Solution().myAtoi(" ")
Solution().myAtoi("+1")
Solution().myAtoi("-")
Solution().myAtoi("?")
Solution().myAtoi("0000123")
Solution().myAtoi("0-1")
Solution().myAtoi("0+1")
Solution().myAtoi("0?1")
Solution().myAtoi("12ds12")
Solution().myAtoi("-5-")

python 实现C atoi函数相关推荐

  1. Python不使用int()函数把字符串转换为数字

    Python不使用int()函数把字符串转换为数字 2018年05月21日 14:18:45 边缘ob边缘ob 阅读数:1035 https://blog.csdn.net/qq_33192555/a ...

  2. 小甲鱼python003答案_小甲鱼:Python学习笔记003_函数

    >>> # 函数 >>> def myFirstFunction(params1,params2...): print("这是我的第一个函数!" ...

  3. python神秘的魔法函数_Python魔法函数

    1.什么是魔法函数 魔法函数即Python类中以__(双下划线)开头,以__(双下划线)结尾的函数,Python提供的函数,可让咱们随意定义类的特性 示例: class Company(object) ...

  4. python 第六章 函数 pta(1)

    1.Multiple-Choice 1.print(type(lambda:3))的输出结果是____. A.<class 'function'> B.<class 'int'> ...

  5. Python最常用的函数、基础语句有哪些?

    作者 | 朱卫军 来源 | Python大数据分析 Python有很多好用的函数和模块,这里给大家整理下我常用的一些方法及语句. 一.内置函数 内置函数是python自带的函数方法,拿来就可以用,比方 ...

  6. python中的pop()函数和popleft()函数

    python中的pop()函数和popleft()函数 首先对于pop而言,它是用于stack中的: stack = [1, 2, 3, 4] print(stack) stack.append(6) ...

  7. python神秘的魔法函数_python进阶之魔法函数

    __repr__ Python中这个__repr__函数,对应repr(object)这个函数,返回一个可以用来表示对象的可打印字符串. 如果我们直接打印一个类,向下面这样 class A(): de ...

  8. 零基础入门学习Python(16)-函数1,Python的乐高积木

    什么是函数? 函数就是把代码打包成不同形状的乐高积木,以便可以发挥想象力进行随意拼装和反复使用 一个程序可以按照不同功能的实现,分割成许许多多的代码块,每一个代码块就可以封装成一个函数 在Python ...

  9. python中使用zip函数基于两个列表数据list创建字典dict数据(Create a dictionary by passing the output of zip to dict)

    python中使用zip函数基于两个列表数据list创建字典dict数据(Create a dictionary by passing the output of zip to dict) 目录

  10. python使用matplotlib可视化函数曲线、设置y轴为对数坐标(log scale)、默认情况下坐标轴为线性坐标

    python使用matplotlib可视化函数曲线.设置y轴为对数坐标(log scale).默认情况下坐标轴为线性坐标 目录

最新文章

  1. CUDA make_float3和make_float4
  2. Android之图片加载框架Picasso源码解析
  3. nginx反向代理tomcat时遇到一个问题
  4. 主存块和cache块关系_Cache(直接相联)
  5. 服务器系统安装iis7.0,Windows2003服务器架IIS7.0怎么安装
  6. [转载] python无法从nltk中调取文本 from nltk.book import *
  7. “鬼才”论文致谢刷屏!感谢我导“似导非导”的指导……
  8. js基础-10-url,src,href的理解
  9. linux下的p2p终结者
  10. DB2 错误码sqlcode对应表
  11. 07、基于ADC0808/ADC0809的多通道电压采集程序设计
  12. 生意参谋 data 16进制数据解析还原
  13. win7升级Powershell到5.1(for flutter)
  14. 4种方法设置Word文档保护
  15. AUTOSAR 网络管理NM
  16. c语言 平均差 标准差,平均差与标准差计算公式中的平均数是()。
  17. 三菱FX系列DPLSY指令使用
  18. 扫码登录的原理和实现
  19. 记账后,如何查看、修改或删除不需要的收支
  20. Web全栈~26.IO

热门文章

  1. lua upvalue
  2. android studio和IDE如何自定义module路径
  3. 浙商证券计算机组成原理,中国海洋大学计算机组成原理期末模拟参考答案.doc...
  4. element中的table相关
  5. jQuery学习笔记(边学边记版本)
  6. java web重定向_Javaweb学习之资源重定向与请求转发
  7. 明基5560 win7 64驱动_这个Win7系统,稳定又纯净!
  8. 处于停机等非正常状态_设备非正常停机管理指导办法
  9. 6 使用soap客户端_SOAP技术应用总结
  10. CMU 15-213 Introduction to Computer Systems学习笔记(3) Floating Point