diff --git a/leetCode Solutions/Q8_atoi/Q8_atoi.java b/leetCode Solutions/Q8_atoi/Q8_atoi.java new file mode 100644 index 0000000..4f87fbb --- /dev/null +++ b/leetCode Solutions/Q8_atoi/Q8_atoi.java @@ -0,0 +1,25 @@ +/* This solution uses the concept and strings and the functions concerning it. */ + +Class answer{ + public int atoi(String s){ + if(s==null) return 0; //in case the String is empty + s=s.trim(); //removes leading spaces + if(s.length()==0) return 0; + int sign=-1; + long ans=0; //taking long since integer might exceed the max/min + int max=Integer.MAX_VALUE; + int min=Integer.MIN_VALUE; + if(s.charAt(0)=='-') sign = -1; + int i = (s.charAt(0)=='+' || s.charAt(0)=='-') ? 1 : 0; //skips an index if a sign is there. + while(i MAX) return MAX; //if ans exceeds max then return max according to the question. + i++; + } + return (int)ans*sign; + } +} + +