Leetcode in Java && Oracle
422 subscribers
8 photos
397 files
400 links
Second channel: @codeforces_java

Let's Develop Together!
Download Telegram
image_2022-11-19_00-56-46.png
87 KB
#medium
#N8. String to Integer (atoi)
problem link
#solution
class Solution {
public int myAtoi(String s) {
if(s.contains("+-")||s.contains("-+")) return 0;
int num=0;
boolean isPos=true, isbrak=true;
for(int i=0;i<s.length();i++){
if(Character.isLetter(s.charAt(i)) || s.charAt(i)=='.' || (s.charAt(i)==' ')&&!isbrak) break;
if(!isbrak && (s.charAt(i)=='-' || s.charAt(i)=='+')) break;
if(s.charAt(i)=='+'||s.charAt(i)=='-') isbrak=false;
if(Character.isDigit(s.charAt(i))){
isbrak=false;
int x=s.charAt(i)-'0';
if(num>Integer.MAX_VALUE/10 || (num==Integer.MAX_VALUE/10 && x>7)){
return isPos?Integer.MAX_VALUE:-Integer.MAX_VALUE-1;
}
num=num*10+x;
}
if(s.charAt(i)=='-') isPos=false;
}

return isPos?num:-num;
}
}

P.s.: F**k finally, after 28 submissions
3👍1