剑指Offer 49. 把字符串转换成整数 (字符串)
2024-10-15 22:26:36
题目描述
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
示例1
输入
+2147483647
1a33
输出
2147483647
0
题目地址
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tqId=11202&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
思路
思路1: 使用了ord函数
考虑首位是否有符号位
遍历字符串,如果字符串为字母,跳出循环
字符0对应的ASCII码为48,对于每个字符,求其ASCII-48
思路2:使用hash将'0'~'9'和数字0~9映射,再遍历
Python
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
if not s:
return 0
sign = 1
if s[0] == '+' or s[0] == '-':
if s[0] == '-':
sign = -1
s = s[1:]
# 思路1
# res = 0
# for x in s:
# if x > '9' or x < '0':
# return 0
# res = res * 10 + ord(x)- 48
# return res * sign
# 思路2:
dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
res = 0
for x in s:
if x > '9' or x < '0':
return 0
res = res * 10 + dict[x]
return res * sign
if __name__ == '__main__':
result = Solution().StrToInt('-123')
print(result)
最新文章
- 使用roslyn代替MSBuild完成解决方案编译
- redis 学习笔记(6)-cluster集群搭建
- EditPlus-CN使用总结
- git 常用操作命令
- 用DataGridView导入TXT文件,并导出为XLS文件
- Atitit 判断判断一张图片是否包含另一张小图片
- emmet插件学习,练习中遇到一些问题
- UML 之 四种关系
- Laravel教程 三:视图变量传递和Blade
- fetch the words from url
- 为 Macbook 增加锁屏热键技巧
- Gas Station [LeetCode]
- 实例讲解Nginx下的rewrite规则
- ABAP更改现有程序
- xshell十大技巧
- swift - use backslash to add the value in the string
- 11-05-sdust-个人赛赛后随想
- python 最基本的的单例模型的实现及应用
- 浅谈URL跳转与Webview安全
- vue学习:安装及创建项目