题目描述

将一个字符串转换成一个整数(实现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)

最新文章

  1. 使用roslyn代替MSBuild完成解决方案编译
  2. redis 学习笔记(6)-cluster集群搭建
  3. EditPlus-CN使用总结
  4. git 常用操作命令
  5. 用DataGridView导入TXT文件,并导出为XLS文件
  6. Atitit 判断判断一张图片是否包含另一张小图片
  7. emmet插件学习,练习中遇到一些问题
  8. UML 之 四种关系
  9. Laravel教程 三:视图变量传递和Blade
  10. fetch the words from url
  11. 为 Macbook 增加锁屏热键技巧
  12. Gas Station [LeetCode]
  13. 实例讲解Nginx下的rewrite规则
  14. ABAP更改现有程序
  15. xshell十大技巧
  16. swift - use backslash to add the value in the string
  17. 11-05-sdust-个人赛赛后随想
  18. python 最基本的的单例模型的实现及应用
  19. 浅谈URL跳转与Webview安全
  20. vue学习:安装及创建项目

热门文章

  1. 20190402Linux高级命令进阶(week1_day2
  2. Docker Compose 介绍安装
  3. 面试常问Spring IOC,不得不会。
  4. ubuntu 16.04 tip
  5. freeswitch编译安装,初探, 以及联合sipgateway, webrtc server的使用场景。
  6. collections.deque
  7. 关于window.onresize
  8. LeetCode--019--删除链表的倒数第N个节点(java)
  9. Java集合框架源码分析(2)LinkedList
  10. day042 css 选择器