LeetCode(8)--String to Integer (atoi)
2015-12-03 21:58
417 查看
题目如下:
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.
解题思路:
首先,要判断该字符串是否可以还换成int类型,然后,判断字符的符号(测试集中有-和+),最后将字符传中的数逐个取出即可。
提交的代码:
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.
解题思路:
首先,要判断该字符串是否可以还换成int类型,然后,判断字符的符号(测试集中有-和+),最后将字符传中的数逐个取出即可。
提交的代码:
public int myAtoi(String str) { int p = 0, ret = 0; while(p < str.length() && Character.isWhitespace(str.charAt(p))) ++p; if(p == str.length()) return 0; boolean negFlag = (str.charAt(p) == '-'); if(str.charAt(p) == '+' || str.charAt(p) == '-') ++p; for(; p<str.length(); ++p) { if(str.charAt(p) > '9' || str.charAt(p) < '0') { break; }else { int digit = str.charAt(p) - '0'; if(!negFlag && ret > (Integer.MAX_VALUE - digit) /10) return Integer.MAX_VALUE; else if(negFlag && ret < (Integer.MIN_VALUE + digit)/10) return Integer.MIN_VALUE; ret = ret * 10 + (negFlag? -digit: digit); } } return ret; }
相关文章推荐
- 生产环境JAVA进程高CPU占用故障排查
- Eclipse 代码提示功能设置
- SVN服务器端安装过程出现“Custom action InstallWMISchemaExecute failed:无法启动服务,原因可能是已被禁用或与其相关联的设备没有启动。”
- div+css3中id和class的命名
- uva 10167 Birthday Cake
- Github fork和pull request概念
- poj--1149--PIGS(最大流经典建图)
- c++中类模板(class template)简单示例 http://blog.csdn.net/richerg85/article/details/7565870
- Java多线程初学笔记
- 利用python中的pandas,sklearn进行数据挖掘 basic_of_datamining
- 模糊测试工具-peachFuzzer
- Happy Number
- Hadoop分布式文件系统(HDFS)详解
- poj--1149--PIGS(最大流经典建图)
- URI和URL的区别
- codeforces604B More Cowbell
- OpenCV 学习(Hough 变换提取直线)
- angular学习
- 网上视频下载
- $.extend()和(function($){….})(jQuery)