Leetcode: String to Integer
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. spoilers alert... click to show requirements for atoi. Requirements for atoi:
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. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
抠细节的题目,特别是 Integer.MIN_VALUE 与 Integer.MAX_VALUE的绝对值并不一样大. 一般要分开处理,但我这里16-17行统一处理也是可行的,原因在于用的是>号,当res 绝对值为2147483647时,给res加正号或者加负号都是可以的,不需要特殊处理;只有当res绝对值为2147483648或更大时才需要特别处理,如果是正数则处理为Integer.MAX_VALUE,如果是负数则处理为Integer.MIN_VALUE(与直接给2147483648加上负号效果一样)。整数一般有两点,一个是正负符号问题,另一个是整数越界问题。
public class Solution {
public int atoi(String str) {
int res = 0;
if (str==null || str.length()==0) return res;
str = str.trim();
if (str.length() == 0) return res;
boolean isNeg = false;
for (int i=0; i<str.length(); i++) {
if (i == 0 && str.charAt(i) == '+') continue;
else if (i == 0 && str.charAt(i) == '-') {
isNeg = true;
continue;
}
else if (str.charAt(i)>='0' && str.charAt(i)<='9') {
int digit = (int)(str.charAt(i) - '0');
if (res > (Integer.MAX_VALUE - digit) / 10) {
return isNeg? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
res = res * 10 + digit;
}
else break;
}
return isNeg? -res : res;
}
}
转载一个不错的解法(跟我差不多):
public int atoi(String str) {
if(str==null)
{
return 0;
}
str = str.trim();
if(str.length()==0)
return 0;
boolean isNeg = false;
int i = 0;
if(str.charAt(0)=='-' || str.charAt(0)=='+')
{
i++;
if(str.charAt(0)=='-')
isNeg = true;
}
int res = 0;
while(i<str.length())
{
if(str.charAt(i)<'0'||str.charAt(i)>'9')
break;
int digit = (int)(str.charAt(i)-'0');
if(isNeg && res>-((Integer.MIN_VALUE+digit)/10))
return Integer.MIN_VALUE;
else if(!isNeg && res>(Integer.MAX_VALUE-digit)/10)
return Integer.MAX_VALUE;
res = res*10+digit;
i++;
}
return isNeg?-res:res;
}
Leetcode: String to Integer的更多相关文章
- LeetCode: String to Integer (atoi) 解题报告
String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...
- [LeetCode] String to Integer (atoi) 字符串转为整数
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- [LeetCode]String to Integer (atoi)
题意:字符串转正数 原题来自:https://leetcode.com/problems/string-to-integer-atoi/ 分析: <程序员面试宝典>上出现的面试题,主要是考 ...
- [Leetcode] String to integer atoi 字符串转换成整数
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- [LeetCode] String to Integer (atoi) 字符串
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- [Leetcode]String to Integer (atoi) 简易实现方法
刚看到题就想用数组做,发现大多数解也是用数组做的,突然看到一个清新脱俗的解法: int atoi(const char *str) { ; int n; string s(str); istrings ...
- leetcode String to Integer (atoi) python
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int "& ...
- leetcode day6 -- String to Integer (atoi) && Best Time to Buy and Sell Stock I II III
1. String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully con ...
- Kotlin实现LeetCode算法题之String to Integer (atoi)
题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 class ...
随机推荐
- Introducing the Accelerated Mobile Pages Project, for a faster, open mobile web
https://googleblog.blogspot.com/2015/10/introducing-accelerated-mobile-pages.html October 7, 2015 Sm ...
- InnoDB , MyISAM :MySQL 5.7 Supported Storage Engines
http://dev.mysql.com/doc/refman/5.7/en/storage-engines.html https://en.wikipedia.org/wiki/ACID https ...
- JS中基本window对象操作
---恢复内容开始--- 一.使用window中的属性时 window.属性,直接跟属性名.而调用window的函数时 window.hanshu(): 要在其函数名后面加括号. 二.windo ...
- 启用“关闭自动根证书更新”,解决Windows系统各种卡顿的问题(Visual studio 卡、远程桌面mstsc卡、SVN卡)
最近,发现在Win7下面一系列操作都会出现卡顿的情况: 1. Visual studio 启动调试和关闭调试时,都会卡上半分钟左右 2. 使用远程桌面mstsc.exe,点击连接时,也会卡上半分钟 ...
- Cocos2d-JS引入其他场景小实例
创建新项目,目标是把LogoNode.js场景引入app.js 新建LogoNode.js var LogoLayer = cc.Layer.extend({ ctor:function () { t ...
- Cocos2d-JS cc.DrawNode用法
app.js var HelloWorldLayer = cc.Layer.extend({ sprite:null, ctor:function () { ///////////////////// ...
- To do
小事{ android values public.xml 树.图的所有遍历方式和优劣 } 大事{ 通读android所有官网文档. android多dex多res开发框架. java AOT(and ...
- Intent Flag(转)
转载自 http://blog.csdn.net/berber78/article/details/7278408 一. intent.setFlags()方法中的参数值含义: 1.FLAG_ACTI ...
- magento安装新插件后后台配置空白解决办法
前段时间,安装完Magento插件以后,就会出现空白或者404问题,在某些运营中的magento网站,安装新插件后后台配置空白解决. 1 将sysytem->toos->Compilati ...
- php创建网站问题
网站在本地浏览的时候链接点击都提示The requested URL was not found on this server. 本地装的wamp,apache和php.ini都是好的 最后更改: 在 ...