您的位置:首页 > 编程语言 > Java开发

【leetcode】【8】String to Integer (atoi)

2016-02-27 10:35 435 查看

一、问题描述

Implement atoi to
convert a string to an integer.

二、问题分析

字符串转换为正数。需要注意①溢出(在处理正数的时候必须首先考虑的问题)②正负③非数字字符④先导空格。时间复杂度为O(n)。

三、Java AC代码

public int myAtoi(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;
}
long res = 0;
while (i < str.length()) {
if (str.charAt(i) < '0' || str.charAt(i) > '9')
break;
int digit = (int) (str.charAt(i) - '0');
res = res * 10 + digit;
if (isNeg && -res < Integer.MIN_VALUE )
return Integer.MIN_VALUE;
else if (!isNeg && res > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
i++;
}
return (int) (isNeg ? -res : res);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode math