-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprobb8.java
More file actions
75 lines (73 loc) · 1.84 KB
/
probb8.java
File metadata and controls
75 lines (73 loc) · 1.84 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
class Solution {
public int myAtoi(String s) {
s.trim();
int n=s.length();
String no="";
boolean flag=false;
for(int i=0;i<n;i++){
char ch=s.charAt(i);
if(ch==' ' || ch=='-' || ch=='+'){
//ignore
if(i!=0 && (s.charAt(i-1)=='-' || s.charAt(i-1)=='+'))
return 0;
}
else if(ch>='0' && ch<='9'){
no=number(s,i);
if(i!=0 && s.charAt(i-1)=='-')
flag=true;
break;
}
else {
return 0;
}
}
long val=0l;
no=removeleadingzeroes(no);
n=no.length();
if(no.length()>=13){
if(flag)
return Integer.MIN_VALUE;
else
return Integer.MAX_VALUE;
}
for(int i=0;i<n;i++){
int a=no.charAt(i)-'0';
val*=10;
val+=a;
}
if(!flag && val>=Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
else if(flag && (val*(-1))<=Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
if(flag)
return (int)val*(-1);
else
return (int)val;
}
public String number(String s,int idx){
int n=s.length();
String ans="";
while(idx<n){
char ch=s.charAt(idx);
if(ch>='0' && ch<='9'){
ans+=ch;
}
else
break;
idx++;
}
return ans;
}
public String removeleadingzeroes(String s){
int n=s.length();
String ans="";
for(int i=0;i<n;i++){
char ch=s.charAt(i);
if(ch!='0')
return s.substring(i);
}
return ans;
}
}