From 6069fc4d655d79ebefda31dc327534c36110ab5a Mon Sep 17 00:00:00 2001 From: ayushijain22 <48030391+ayushijain22@users.noreply.github.com> Date: Tue, 6 Oct 2020 08:45:07 +0530 Subject: [PATCH] Create String to integer(atoi) --- leetcode/String to integer(atoi) | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 leetcode/String to integer(atoi) diff --git a/leetcode/String to integer(atoi) b/leetcode/String to integer(atoi) new file mode 100644 index 00000000..b6f6f8f0 --- /dev/null +++ b/leetcode/String to integer(atoi) @@ -0,0 +1,27 @@ +class Solve { + public int myAtoi(String str) { + int i = 0; + int sign = 1; + int result = 0; + if (str.length() == 0) return 0; + + + while (i < str.length() && str.charAt(i) == ' ') + i++; + + + if (i < str.length() && (str.charAt(i) == '+' || str.charAt(i) == '-')) + sign = (str.charAt(i++) == '-') ? -1 : 1; + + + while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') { + if (result > Integer.MAX_VALUE / 10 || + (result == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > Integer.MAX_VALUE % 10)) { + return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; + } + result = result * 10 + (str.charAt(i++) - '0'); + } + return result * sign; + + } +}