-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
84 lines (81 loc) · 2.96 KB
/
Copy pathsolution.java
File metadata and controls
84 lines (81 loc) · 2.96 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// 8. String to Integer (atoi)
// https://leetcode.com/problems/string-to-integer-atoi/
// Medium | Java | Accepted 2026-08-13
// Runtime 1 ms | Memory 44.1 MB
class Solution {
public int myAtoi(String s) {
int ans = 0;
int i = 0;
boolean negative = false; //Flag to check if the number is negative or not
while(i<s.length())
{
char t = s.charAt(i);
if(!Character.isDigit(t) && t!='-' && t!='+' && t!=' ') //If the character isn't whitespace and not a digit or a sign, then end the iteration immediately
{
break;
}
if(t==' ') //If the character is whitespace, just keep iterating
{
i++;
continue;
}
if(t=='+') //If the character is a sign, check if the next character is a digit
//If it isn't, immediately return 0
{
if(i+1<s.length() && !Character.isDigit(s.charAt(i+1)))
{
return 0;
}
i++;
continue;
}
if(t=='-')
{
if(i+1<s.length() && Character.isDigit(s.charAt(i+1))) //If the character is a sign, check if the next character is a digit
//If it isn't, immediately return 0
//Also set the negative flag to true if the next character is a digit
{
negative = true;
}
else
{
return 0;
}
i++;
continue;
}
if(Character.isDigit(t)) //Now that all the signs and whitespace are taken care of, start iterating through the actual integer if there are digits
{
while(i<s.length() && s.charAt(i)-'0'==0) //Take care of leading zeroes first
{
i++;
}
while(i<s.length()&&Character.isDigit(s.charAt(i)))
{
int prev = ans;
if(negative)
{
if(ans < Integer.MIN_VALUE/10 || (ans==Integer.MIN_VALUE/10 && (s.charAt(i)-'0')>8))
{
return Integer.MIN_VALUE;
}
ans*=10;
ans-=(s.charAt(i)-'0');
}
else
{
if(ans > Integer.MAX_VALUE/10 || (ans==Integer.MAX_VALUE/10 && (s.charAt(i)-'0')>7))
{
return Integer.MAX_VALUE;
}
ans*=10;
ans+=(s.charAt(i)-'0');
}
i++;
}
break;
}
}
return ans;
}
}