FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-algorithms/src/StringToIntegerAtoi.java at master · anishLearnsToCode/leetcode-algorithms · GitHub
anishLearnsToCode
/
leetcode-algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
17
Star
98
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode-algorithms
/
src
/
StringToIntegerAtoi.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
45 lines (38 loc) · 1.51 KB
Breadcrumbs
leetcode-algorithms
/
src
/
StringToIntegerAtoi.java
Copy path
File metadata and controls
45 lines (38 loc) · 1.51 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
// https://leetcode.com/problems/string-to-integer-atoi
// T:O(|input|)
// S:O(1)
public
class
StringToIntegerAtoi
{
public
int
myAtoi
(
String
input
) {
int
sign
=
1
;
int
result
=
0
;
int
index
=
0
;
int
n
=
input
.
length
();
// Discard all spaces from the beginning of the input string.
while
(
index
<
n
&&
input
.
charAt
(
index
) ==
' '
) {
index
++;
}
// sign = +1, if it's positive number, otherwise sign = -1.
if
(
index
<
n
&&
input
.
charAt
(
index
) ==
'+'
) {
index
++;
}
else
if
(
index
<
n
&&
input
.
charAt
(
index
) ==
'-'
) {
sign
= -
1
;
index
++;
}
// Traverse next digits of input and stop if it is not a digit
while
(
index
<
n
&&
Character
.
isDigit
(
input
.
charAt
(
index
))) {
int
digit
=
input
.
charAt
(
index
) -
'0'
;
// Check overflow and underflow conditions.
if
((
result
>
Integer
.
MAX_VALUE
/
10
) ||
(
result
==
Integer
.
MAX_VALUE
/
10
&&
digit
>
Integer
.
MAX_VALUE
%
10
)) {
// If integer overflowed return 2^31-1, otherwise if underflowed return -2^31.
return
sign
==
1
?
Integer
.
MAX_VALUE
:
Integer
.
MIN_VALUE
;
}
// Append current digit to the result.
result
=
10
*
result
+
digit
;
index
++;
}
// We have formed a valid number without any overflow/underflow.
// Return it after multiplying it with its sign.
return
sign
*
result
;
}
}
Back
|
FazBrowse Home
|
New Git URL