-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0008_String-to-Integer-atoi.java
43 lines (33 loc) · 1.04 KB
/
0008_String-to-Integer-atoi.java
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
/*
* 8. String to Integer (atoi)
* Problem Link: https://leetcode.com/problems/string-to-integer-atoi/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public int myAtoi(String s) {
long number = 0;
boolean isPositive = true;
int i = 0;
while ( i < s.length() && s.charAt(i) == ' ') {
i++;
}
if (i < s.length() && (s.charAt(i) == '-' || s.charAt(i) == '+')) {
isPositive = s.charAt(i) == '+';
i++;
}
while (i < s.length() && Character.isDigit(s.charAt(i)) ) {
number = number * 10 + s.charAt(i) - '0';
if (number > Integer.MAX_VALUE){
return isPositive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
i++;
}
if (!isPositive) number *= -1;
return (int)number;
}
}