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

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++

 1 #include<algorithm>
 2 using namespace std;
 3 class Solution {
 4 public:
 5     int myAtoi(string str) {
 6         bool isFirstChar = true, isNagetive = false;
 7         long result = 0;
 8         for (int i = 0; i < str.length(); i++) {
 9             if (isFirstChar&&str[i] == ' ')
10                 continue;
11             if (isFirstChar&&str[i] == '-') {
12                 isNagetive = true;
13                 isFirstChar = false;
14                 continue;
15             }
16             if (isFirstChar&&str[i] == '+') {
17                 isFirstChar = false;
18                 continue;
19             }
20             int temp = str[i] - '0';
21             if (temp >= 0 && temp <= 9)
22             {
23                 if (isNagetive) {
24                     result = result * 10 - temp;
25                 }
26                 else result = result * 10 + temp;
27                 if (result > INT_MAX)
28                     return INT_MAX;
29 
30                 if (result < INT_MIN)
31                     return INT_MIN;
32             }
33             else break;
34             isFirstChar = false;
35         }
36         return (int)result;
37     }
38 };
原文地址:https://www.cnblogs.com/tonyluis/p/4456802.html