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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51 |
public class Solution { public
int atoi(String str) { int
result = 0 ; int
slen = str.length(); if (str != null
&& slen != 0 ){ //remove the leading empty characters int
i = 0 ; while (str.charAt(i) == ‘ ‘ ) ++i; //find the sign of the number boolean
isNegative = false ; if (str.charAt(i) == ‘+‘ ) ++i; if (str.charAt(i) == ‘-‘ ) { ++i; isNegative = true ; } StringBuffer stb = new
StringBuffer(); while (i < slen){ if (isNumberDigit(str.charAt(i))){ stb.append(str.charAt(i)); ++i; } else break ; } long
tempresult = 0 ; //the type of this variable must be long long
digit = 1 ; //the type of this variable must be long too int
j = stb.length() - 1 ; while (j >= 0 ){ tempresult +=(stb.charAt(j) - ‘0‘ ) * digit; digit *= 10 ; --j; if (tempresult == Integer.MAX_VALUE) return
isNegative ? Integer.MIN_VALUE + 1
: Integer.MAX_VALUE; if (tempresult >= ( long )Integer.MAX_VALUE + 1 ) return
isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE; } result = isNegative ? ( int )( 0
- tempresult) : ( int )(tempresult); } return
result; } public
boolean isNumberDigit( char
c){ return
c >= ‘0‘
&& c <= ‘9‘ ; } } |
leetcode--String to Integer (atoi)
原文:http://www.cnblogs.com/averillzheng/p/3561566.html