leetcode第8题——*String to Integer (atoi)
2016-01-01 11:07
344 查看
题目
Implement atoi to convert a string to an integer.Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
思路
题目大意是将字符串转换为整型,分正负数的情况,忽略空白字符和非数字字符,比如:“ -1234a”转换为-1234,"jsk903"转换为903,"2345678"转为2345678......如果超出整型数据范围则取0x7FFFFFFF或0x80000000. 题目本身很简单,先将空字符和符号位取出,然后依次将每位上的结果乘以10再加入到新的结果中。要注意的是溢出处理,可以定义一个长整型变量res保存结果,如果res超出整型范围则返回0x7FFFFFFF或0x80000000,如果没有超出则将res转换为整型再返回即可。代码
Python
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ strLen = len(str) if str == '': return 0 i = 0 while (i < strLen): #跳过空白字符 if(str[i] == ' '): i += 1 else: break if i == strLen: return 0 signal = 1 if str[i] == '+': signal = 1 i += 1 elif str[i] == '-': signal = -1 i += 1 res = 0 #Python不声明变量类型,数字超出int型范围自动转为长整型,因此要在80000000前加负号 maxInt = 0x7FFFFFFF minInt = -0x80000000 while (i < strLen): if ((str[i] >= '0') & (str[i] <= '9')): #是数字则乘以权值并相加 res = res*10 + signal*(int(str[i])) else: return res #这里可加语句用来调试print 'str[%d]=%s,res=%d'%(i,str[i],res) if(res > maxInt): return maxInt elif(res < minInt): return minInt i += 1; return res
Java
public class Solution { public int myAtoi(String str) { int strLen = str.length(); if (str == "") return 0; int i = 0; while (i < strLen){ if(str.charAt(i) == ' ') i++; else break; } if (i == strLen) return 0; int signal = 1; if (str.charAt(i) == '+'){ signal = 1; i++; } else if (str.charAt(i) == '-'){ signal = -1; i++; } long res = 0; int maxInt = 0x7FFFFFFF; int minInt = 0x80000000; while (i < strLen){ if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){ //是数字则乘以权值并相加 res = res*10 + signal*(str.charAt(i) - '0'); } else return (int)res; if (res > maxInt || res < minInt) return res>0?maxInt:minInt; i++; } return (int)res; } }
相关文章推荐
- Eclipse搭建android环境及Genymotion模拟器安装问题解决方法
- hadoop2.x 常用端口及定义方法
- Java在制作jar包时引用第三方jar包的方法
- activiti数据库表结构全貌解析
- Hadoop 1.x 与 2.x 中 fsimage 和 edits 合并实现
- 整数分隔
- Java对象的硬、软、弱和虚引用
- 左式堆--C语言实现
- python批量下载图片的三种方法
- android eclipse 环境搭建
- Hadoop NameNode元数据相关文件目录解析
- Eclipse启动时出现错误 An internal error occurred during: “Updating indexes”
- Linux系统下对硬盘分区进行扩容的方法总结
- Visual Studio Code之常备快捷键
- Apache不记录指定类型日志
- Jquery 获取 radio选中值
- 【PAT】1007 Maximum Subsequence Sum (25) 最大连续子序列和 +记录位置
- okhttp使用入门
- Internet资源标识——快看看你认识这三个家伙不!?
- Lisp---数列反转