-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path13thJune(II).java
More file actions
55 lines (40 loc) · 1.56 KB
/
Copy path13thJune(II).java
File metadata and controls
55 lines (40 loc) · 1.56 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
// import java.lang.Character;
public class stringToInteger_aoti {
static int aoti(String s){
int sign = 1; // 1 for positive and -1 for negative
int result = 0; // store result
int index = 0; // checking cases for whitespaces
int n = s.length();
//check white spaces and trim them
while(index<n && s.charAt(index)==' '){
index++; // index is reaching to starting digit or character
}
// checking for signs
if(index<n && s.charAt(index)=='-'){
sign = -1;
index++;
}
else if(index<n && s.charAt(index)=='+'){
sign = 1;
index++;
}
//main logic
while(index<n && Character.isDigit(s.charAt(index))){ // will only traverse if it is a digit
int digit = s.charAt(index)-'0'; // '4'-'0'=4.....AscII
// to check overflow and underflow
if((result>Integer.MAX_VALUE/10) || result==Integer.MAX_VALUE/10 && digit>Integer.MAX_VALUE%10){
// we are dividing by 10 because in next iteraion we are appending a number after multiplying it by 10
return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
}
result = 10*result+digit; // to make a number
index++;
}
// last task is to append the sign to the result
return result*sign;
}
public static void main(String[] args) {
String s= " +42";
System.out.println(aoti(s));
}
}
// OP = 42