From 600120d1b523c56bc1c2b9bb261fb55a9f761df7 Mon Sep 17 00:00:00 2001 From: Ragini Singh <87365673+raginiisingh@users.noreply.github.com> Date: Sun, 2 Oct 2022 23:04:38 +0530 Subject: [PATCH] Added the solution to the question in Java. --- leetCode Solutions/Q8_atoi/Q8_atoi.java | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 leetCode Solutions/Q8_atoi/Q8_atoi.java 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; + } +} + +