您的位置:首页 > 编程语言 > C语言/C++

【JAVA、C++】 LeetCode 008 String to Integer (atoi)

2015-04-25 21:59 453 查看
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.

解题思路:

本题难度并不大,比较无聊,主要是要考虑到几个边界条件,本人也是提交数次才通过的。

JAVA代码如下:

static public int myAtoi(String str) {
if (str == null )
return 0;
str = str.trim();
if(str.length()==0)
return 0;
boolean isNagetive = false;

if (str.charAt(0) == '-')
isNagetive = true;
long result = 0;
for (int i = 0; i < str.length(); i++) {
if(i==0&&(str.charAt(0)=='-'||str.charAt(0)=='+'))
continue;
int temp = str.charAt(i) - '0';
if (temp >= 0 && temp <= 9)
{
if(isNagetive){
result=result * 10 - temp;
}
else result = result * 10 + temp;
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;

if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}

else break;
}
return (int) result;
}


C++

#include<algorithm>
using namespace std;
class Solution {
public:
int myAtoi(string str) {
bool isFirstChar = true, isNagetive = false;
long result = 0;
for (int i = 0; i < str.length(); i++) {
if (isFirstChar&&str[i] == ' ')
continue;
if (isFirstChar&&str[i] == '-') {
isNagetive = true;
isFirstChar = false;
continue;
}
if (isFirstChar&&str[i] == '+') {
isFirstChar = false;
continue;
}
int temp = str[i] - '0';
if (temp >= 0 && temp <= 9)
{
if (isNagetive) {
result = result * 10 - temp;
}
else result = result * 10 + temp;
if (result > INT_MAX)
return INT_MAX;

if (result < INT_MIN)
return INT_MIN;
}
else break;
isFirstChar = false;
}
return (int)result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: