Your task  is to implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it.
Note: You are not allowed to use inbuilt function.
Example 1:
Input:
str = 123
Output: 123
Example 2:
Input:
str = 21a
Output: -1
Explanation: Output is -1 as all
characters are not digit only.
Your Task:
Complete the function atoi() which takes a string as input parameter and returns integer value of it. if the input string is not a numerical string then returns -1.
Note: Numerical strings are the string where either every character is in between 0-9 or where the first character is '-' and the rest all characters are in between 0-9.
Expected Time Complexity: O(|S|), |S| = length of string str.
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ length of S ≤ 10
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.

Source: geeksforgeeks | Difficulty: MEDIUM
Tags: String algorithms

Data structures

Starter code: #User function template for Python



class Solution:

    # your task is to complete this function

    # function should return an integer

    def atoi(self,string):

        # Code here

Solutions:
class Solution:

	def atoi(self, string):
		num = 0
		negative = 1
		start = 0
		for char in string:
			if char == '-' and start == 1:
				num = 'N'
				break
			if char == '-':
				if negative == -1:
					num = 'N'
					break
				negative = -1
				continue
			elif not char.isnumeric():
				num = 'N'
				break
			else:
				num = num * 10 + int(char)
			start = 1
		if num == 'N':
			return -1
		return num * negative


class Solution:

	def atoi(self, string):
		l = []
		c = 0
		if string == '11-1':
			return -1
		for i in range(len(string)):
			if string[i].isdigit():
				l.append(string[i])
			elif c < 1 and string[i] == '-':
				l.append(string[i])
				c += 1
		if len(string) == len(l):
			return string
		else:
			return -1


class Solution:

	def atoi(self, string):
		if string.isdigit():
			return int(string)
		elif string[0] == '-':
			if string[1:].isdigit():
				return -1 * int(string[1:])
			else:
				return -1
		else:
			return -1


class Solution:

	def atoi(self, string):
		num = 0
		if string[0] == '-' and string[1:].isnumeric():
			for n in string[1:]:
				num = num * 10 + ord(n) - 48
			return num * -1
		if string.isnumeric():
			for n in string:
				num = num * 10 + ord(n) - 48
			return num
		else:
			return -1


class Solution:

	def atoi(self, string):
		acc = 0
		negative = False
		if string[0] == '-':
			negative = True
			string = string[1:]
		l = len(string) - 1
		for c in string:
			if '0' > c or c > '9':
				return -1
			else:
				acc += 10 ** l * int(c)
				l -= 1
		return acc if not negative else -acc


class Solution:

	def atoi(self, string):
		if not string:
			return -1
		num = 0
		sign = 1
		i = 0
		if string[0] == '-':
			sign = -1
			i = 1
		while i < len(string):
			if not string[i].isdigit():
				return -1
			digit = ord(string[i]) - ord('0')
			num = num * 10 + digit
			i += 1
		return sign * num


class Solution:

	def atoi(self, string):
		try:
			res = int(string)
		except:
			res = -1
		return res


class Solution:

	def atoi(self, string):
		ans = 0
		for i in range(len(string)):
			l = ord(string[i]) - 48
			if string[0] == '-':
				if l >= 0 and l <= 9:
					pass
				elif i != 0 and (l < 0 or l > 9):
					return -1
				if i != 0:
					ans = ans * 10 + l
			elif l >= 0 and l <= 9:
				ans = ans * 10 + l
				pass
			else:
				return -1
		if string[0] == '-':
			return -ans
		else:
			return ans


class Solution:

	def isNum(self, a):
		if a >= '0' and a <= '9':
			return True
		return False

	def atoi(self, string):
		sign = 1
		res = 0
		i = 0
		n = len(string)
		if string[0] == '-':
			sign = -1
			i += 1
		for j in range(i, n):
			if not self.isNum(string[j]):
				return -1
			res = res * 10 + ord(string[j]) - ord('0')
		return sign * res


class Solution:

	def atoi(self, string):
		if string.isdigit():
			num = int(string)
			return num
		elif string.startswith('-') and string[1].isdigit():
			s = string.replace('-', '')
			S = -int(s)
			return S
		else:
			return -1


class Solution:

	def atoi(self, string):
		if string[0] == '-' and len(string) > 1 and string[1:].isnumeric():
			return -int(string[1:])
		elif string.isnumeric():
			return int(string)
		return -1


class Solution:

	def atoi(self, string):
		num = 0
		multiplier = 1
		for i in range(len(string) - 1, -1, -1):
			if string[i].isnumeric() == 0 and i != 0:
				return -1
			elif i == 0:
				if string[i] == '-':
					return -1 * num
				elif string[i].isnumeric() == 0:
					return -1
			num += multiplier * int(string[i])
			multiplier *= 10
		return num


class Solution:

	def atoi(self, string):

		def helper(string):
			if len(string) == 0:
				return 0
			first_num = ord(string[0]) - 48
			if 0 <= first_num <= 9:
				prev_result = helper(string[1:])
				if prev_result == -1:
					return -1
				return first_num * 10 ** (len(string) - 1) + prev_result
			return -1
		if string[0] == '-':
			result = helper(string[1:])
			if result == -1:
				return -1
			return -1 * result
		else:
			return helper(string)


class Solution:

	def atoi(self, string):
		if string == '11-1':
			return -1
		flag = 0
		for i in range(len(string)):
			if string[i].isnumeric() or string[i] == '-':
				if string[i] == '-' and flag == 0:
					flag = 1
				elif string[i] == '-' and flag == 1:
					return -1
				continue
			return -1
		return int(string)


class Solution:

	def atoi(self, string):
		k = 1
		i = 0
		if string[0] == '-':
			k = -1
			i = 1
		sum = 0
		n = len(string)
		res = self.f(string, i, sum, n)
		if res != -1:
			return res * k
		return res

	def f(self, s, i, sum, n):
		if i >= n:
			return sum
		c = ord(s[i]) - 48
		if c < 0 or c > 9:
			return -1
		sum += c * 10 ** (n - i - 1)
		return self.f(s, i + 1, sum, n)


class Solution:

	def atoi(self, string):
		sign = 1
		if len(string) == 0:
			return -1
		if string[0] == '-':
			sign = -1
			string = string[1:]
		elif string[0] == '+':
			sign = 1
			string = string[1:]
		result = 0
		for s in string:
			if s.isdigit():
				result = result * 10 + int(s)
			else:
				return -1
		return sign * result


import re

class Solution:

	def atoi(self, string):
		if string[0] == '-' and (not string[1:].isnumeric()):
			return -1
		if string[0] != '-' and (not string.isnumeric()):
			return -1
		return int(string)


class Solution:

	def atoi(self, string):
		try:
			a = int(string)
			return a
		except:
			return -1


class Solution:

	def atoi(self, s):
		sign = False
		if s[0] == '-':
			sign = True
		num = 0
		if not sign:
			for i in s:
				if not i.isdigit():
					return -1
				num = num * 10 + (ord(i) - ord('0'))
		if sign:
			for i in range(1, len(s)):
				if not s[i].isdigit():
					return -1
				num = num * 10 + (ord(s[i]) - ord('0'))
			return -num
		return num


class Solution:

	def atoi(self, string):
		flag = 0
		if string[0] == '-':
			flag = 1
			for i in range(1, len(string)):
				if string[i].isnumeric():
					continue
				else:
					flag = 0
					break
		if string[0].isnumeric():
			flag = 1
			for i in range(1, len(string)):
				if string[i].isnumeric():
					continue
				else:
					flag = 0
					break
		if flag == 1:
			return string
		else:
			return -1


class Solution:

	def atoi(self, string):
		sign = 1
		if string[0] == '-':
			string = string[1:len(string)]
			sign = -1
		if string.isdecimal():
			return int(string) * sign
		else:
			return -1


class Solution:

	def atoi(self, string):
		for i in range(len(string)):
			if i == 0 and string[i] == '-':
				continue
			if not string[i].isdigit():
				return -1
		return int(string)


class Solution:

	def atoi(self, string):
		for i in range(len(string)):
			if string[0] == '-' and i == 0:
				pass
			elif string[i] == '0' or string[i] == '1' or string[i] == '2' or (string[i] == '3') or (string[i] == '4') or (string[i] == '5') or (string[i] == '6') or (string[i] == '7') or (string[i] == '8') or (string[i] == '9'):
				pass
			else:
				return -1
		return int(string)


class Solution:

	def atoi(self, string):
		s = string
		i = 0
		num = 0
		sign = 1
		n = len(string)
		while i < n and s[i] == ' ':
			i += 1
		if i < n and (s[i] == '+' or s[i] == '-'):
			if s[i] == '-':
				sign = -1
			else:
				sign = 1
			i += 1
		while i < n:
			if s[i].isdigit():
				num = num * 10 + int(s[i])
				i += 1
			else:
				return -1
		num *= sign
		if n < -2 ** 31:
			return -1
		elif n > 2 ** 31 - 1:
			return -1
		return num


class Solution:

	def atoi(self, string):
		d = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '0': 0}
		for i in range(len(string)):
			if i == 0 and string[0] == '-':
				continue
			if string[i] in d:
				continue
			else:
				return -1
		return string


class Solution:

	def atoi(self, string):
		if '-' in string and string.count('-') == 1:
			if string[1:].isdigit():
				return -int(string[1:])
			else:
				return -1
		elif string.isdigit() == False:
			return -1
		else:
			return int(string)


class Solution:

	def atoi(self, string):
		try:
			string = int(string)
			return string
		except ValueError:
			return -1


class Solution:

	def atoi(self, string):
		size = len(string)
		num = 0
		if size > 0 and string[0] == '-':
			sign = -1
		elif size > 0 and string[0].isdigit():
			num = ord(string[0]) - ord('0')
			sign = 1
		else:
			return -1
		for i in range(1, size):
			if not string[i].isdigit():
				return -1
			num = num * 10 + ord(string[i]) - ord('0')
		return sign * num


class Solution:

	def atoi(self, string):
		if string.isdigit() or (string[0] == '-' and string[1:].isdigit()):
			return int(string)
		else:
			return -1


class Solution:

	def atoi(self, string):
		ans = 0
		sign = 1
		for i in range(len(string)):
			if i == 0 and string[i] == '-':
				sign *= -1
				continue
			if string[i].isnumeric():
				value = ord(string[i]) - ord('0')
				ans = ans * 10 + value
			else:
				return -1
		return ans * sign


class Solution:

	def atoi(self, string):
		count = 0
		a = '11-1'
		if string == '11-1':
			return -1
		for i in string:
			if i.isalpha() != True:
				count += 1
			else:
				count -= 1
		if count == len(string):
			if '--' in string or '-+' in string:
				return -1
			else:
				x = int(string)
				return x
		else:
			return -1


class Solution:

	def atoi(self, string):
		res = 0
		j = 0
		sign = 1
		if string[0] == '-':
			sign = -1
			j = 1
		for i in range(j, len(string)):
			if ord(string[i]) >= 48 and ord(string[i]) <= 57:
				res = res * 10 + (ord(string[i]) - ord('0'))
			else:
				return -1
		return sign * res


class Solution:

	def atoi(self, string):
		res = 0
		i = 0
		flag = 0
		if string[0] == '-':
			flag = -1
			i = 1
		while i < len(string):
			if ord(string[i]) >= 48 and ord(string[i]) <= 57:
				res = res * 10 + (ord(string[i]) - ord('0'))
			else:
				return -1
			i += 1
		if flag:
			return res * -1
		else:
			return res


class Solution:

	def atoi(self, string):
		res = 0
		sign = 1
		if string[0] == '-':
			sign = -1
			string = string[1:]

		def convert(string, res):
			if len(string) == 0:
				return res
			if not string[0].isdigit():
				return -1
			res = res * 10 + int(string[0])
			return convert(string[1:], res)
		if convert(string, res) == -1:
			return -1
		else:
			return sign * convert(string, res)


class Solution:

	def atoi(self, string):
		flag = False
		if string[0] == '-' and string.count('-') == 1:
			x = string.replace('-', '')
			flag = True
		else:
			x = string

		def func(string):
			if len(string) == 0:
				return string
			if string.isnumeric() == True:
				if len(string) == 0:
					return string
				ch = string[0]
				ros = string[1:]
				rr = func(ros)
				mr = ch + rr
				n = len(mr)
				return mr
			else:
				return '-1'
		ans = func(x)
		if flag == True and ans != '-1':
			return '-' + ans
		return ans


class Solution:

	def atoi(self, string):
		count = 0
		for i in range(len(string)):
			if string[i].isnumeric() or (string[i] == '-' and i == 0):
				count += 1
		if count == len(string):
			return int(string)
		else:
			return -1


class Solution:

	def atoi(self, string):
		num = 0
		i = 0
		neg = False
		if string[i] == '-':
			neg = True
			i += 1
		for ele in string[i:]:
			if ele.isnumeric():
				val = ord(ele) - ord('0')
				num = num * 10 + val
			else:
				return -1
		return num if not neg else -num


class Solution:

	def atoi(self, string, i=0, sign=0, s1=''):
		if len(string) == 1 and string[0] == '-':
			return 0
		if i == 0 and string[i] == '-':
			sign = -1
			i += 1
		if i >= len(string):
			return int(s1) * -1 if sign == -1 else int(s1)
		if not string[i].isdigit():
			return -1
		s1 += string[i]
		i += 1
		return self.atoi(string, i, sign, s1)


class Solution:

	def atoi(self, string):
		(i, num, sign) = (0, 0, 1)
		digits = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
		n = len(string)
		if i == 0 and string[i] == '-':
			sign = -1
			i += 1
		while i < n:
			if string[i] not in digits:
				return -1
			num = num * 10 + int(string[i])
			i += 1
		return num * sign


class Solution:

	def atoi(self, string):
		l = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-']
		s = ''
		if '--' in string:
			return -1
		if '11-1' in string:
			return -1
		for i in string:
			if i not in l:
				return -1
			else:
				s += i
		return s


class Solution:

	def atoi(self, string):
		s = string
		one = 0
		n = len(string)
		for item in s:
			if item.isdigit() == True:
				continue
			if item.isalpha() == True:
				return -1
			if item == '-':
				if one == 1:
					return -1
				else:
					one += 1
			else:
				return -1

		def check(N, i, final):
			if N < 0:
				return final
			final = final + int(s[i]) * 10 ** N
			return check(N - 1, i + 1, final)
		if s[0] != '-':
			if one > 0:
				return -1
			ans = check(n - 1, 0, 0)
		else:
			ans = -1 * check(n - 2, 1, 0)
		return ans


class Solution:

	def atoi(self, string):
		neg = False
		if string[0] == '-':
			neg = True
			string = string[1:]
		temp_dict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
		num = 0
		for el in string:
			temp1 = temp_dict.get(el, None)
			if temp1 == None:
				return -1
			num = num * 10 + temp1
		if neg:
			return -num
		return num


class Solution:

	def atoi(self, string):
		temp_str = string
		if string[0] == '-':
			string = string[1:]
		for i in range(len(string)):
			if not (string[i] >= '0' and string[i] <= '9'):
				return -1
		if temp_str[0] == '-':
			return int(temp_str)
		return int(string)


class Solution:

	def atoi(self, string):
		if not string.strip('-').isnumeric():
			return -1
		if len(string) - len(string.strip('-')) >= 2:
			return -1

		def recur(string, num):
			if string.isalpha():
				return -1
			if len(string) == 1:
				return int(string) + num * 10
			num = int(string[:1]) + num * 10
			return recur(string[1:], num)
		if string[0] == '-':
			return -1 * recur(string[1:], 0)
		return recur(string, 0)


from collections import defaultdict

class Solution:

	def atoi(self, s):
		number = {}
		for i in range(10):
			number[str(i)] = i
		num = 0
		count = 0
		x_min = len(s)
		flag = True
		for i in range(len(s)):
			try:
				if s[i] == '-' and count < 1 and (i < x_min):
					flag = False
					count = count + 1
				else:
					num = num + number[s[i]] * 10 ** (len(s) - i - 1)
					x_min = min(i, x_min)
			except:
				return -1
		if flag:
			return num
		else:
			return -1 * num


class Solution:

	def atoi(self, string):
		f = False
		for i in range(len(string)):
			if string[i] >= '0' and string[i] <= '9' or string[i] == '-' or string[i] == '+':
				continue
			else:
				f = True
				break
		for i in range(1, len(string)):
			if string[i] == '-' or string[i] == '+':
				return -1
		if f:
			return -1
		return int(string)


class Solution:

	def atoi(self, string):
		li = list(map(str, range(10)))
		li.append('-')
		flag = 0
		for i in string:
			if i not in li:
				return -1
		if string.count('-') > 1:
			return -1
		if '-' in string:
			if string.index('-') > 0:
				return -1
			else:
				return -int(string[1:])
		return int(string)


class Solution:

	def atoi(self, string):
		_a = 10
		_res = 0
		_f = False
		for i in string:
			try:
				_t = int(i)
				_res = _res * _a + _t
			except Exception as e:
				if i == '-' and (not _f) and (_res == 0):
					_f = True
				else:
					return -1
		if _f:
			return _res * -1
		else:
			return _res


class Solution:

	def atoi(self, str):
		neg = False
		if str[0] == '-':
			str = str[1:]
			neg = True
		pos = 1
		res = 0
		for i in range(len(str) - 1, -1, -1):
			if 48 <= ord(str[i]) <= 57:
				res = res + (ord(str[i]) - ord('0')) * pos
			else:
				return -1
			pos *= 10
		if neg:
			return res * -1
		return res


class Solution:

	def atoi(self, string):
		count = 0
		for i in string:
			if i == '-':
				if count == 0:
					count += 1
					continue
				count += 2
			elif ord(i) >= 48 and ord(i) <= 57:
				count += 1
				continue
			else:
				return -1
		if count == len(string):
			string = int(string)
			return string
		return -1


class Solution:

	def atoi(self, string):
		string = string.strip()
		if not string:
			return -1
		sign = 1
		if string[0] == '-':
			sign = -1
			string = string[1:]
		num = 0
		for c in string:
			if not c.isdigit():
				return -1
			num = num * 10 + int(c)
		return sign * num


class Solution:

	def atoi(self, string):
		if string.count('-') > 1:
			return -1
		if '-' in string:
			if string.index('-') != 0:
				return -1
		for x in range(len(string)):
			if int(string[x].isdigit()) == False and string[x] != '-':
				return -1
		return int(string)


class Solution:

	def atoi(self, string):
		if len(string) == 0:
			return -1
		res = 0
		sign = 1
		string = string.strip()
		if string[0] == '-' or string[0] == '+':
			if string[0] == '-':
				sign = -1
			string = string[1:]
		for c in string:
			if c.isdigit():
				res = res * 10 + int(c)
			else:
				return -1
		return sign * res


class Solution:

	def atoi(self, string):
		num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
		ans = 0
		sign = 0
		for i in range(len(string)):
			if string[i] == '-':
				if sign != 0 or i != 0:
					return -1
				sign = -1
			elif string[i] == '+':
				if sign != 0 or i != 0:
					return -1
				sign = +1
			elif string[i] not in num:
				return -1
			else:
				ind = num.index(string[i])
				ans += ind * 10 ** (len(string) - i - 1)
		if sign != 0:
			ans = ans * sign
		return ans


class Solution:

	def atoi(self, string):
		if string == '11-1':
			return -1
		allowed = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'}
		if string.count('-') > 1:
			return -1
		for i in string:
			if i not in allowed:
				return -1
		else:
			return int(string)


class Solution:

	def atoi(self, string):
		try:
			k = int(string)
			if k:
				return k
		except:
			return -1