From ccd114deb65c390203a6d58088a7657ef1cf9bfb Mon Sep 17 00:00:00 2001 From: Elements05 <116535389+Elements05@users.noreply.github.com> Date: Tue, 25 Oct 2022 23:58:41 +0530 Subject: [PATCH] Create string_to_integer.cpp string to integer atoi --- standard questions/string_to_integer.cpp | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 standard questions/string_to_integer.cpp diff --git a/standard questions/string_to_integer.cpp b/standard questions/string_to_integer.cpp new file mode 100644 index 0000000..f198ad6 --- /dev/null +++ b/standard questions/string_to_integer.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + int myAtoi(string s) { + + const int len = s.size(); + + if(len == 0){ + return 0; + } + + int index = 0; + while(index < len && s[index] == ' '){ + ++index; + } + + if(index == len){ + return 0; + } + + char ch; + bool isNegative = (ch = s[index]) == '-'; + + if(isNegative || ch == '+'){ + ++index; + } + + const int maxLimit = INT_MAX / 10; + int result = 0; + while(index < len && isDigit(ch = s[index])){ + + int digit = ch - '0'; + + if(result > maxLimit || (result == maxLimit && digit > 7)){ + return isNegative ? INT_MIN : INT_MAX; + } + + result = (result * 10) + digit; + + ++index; + } + + return isNegative ? -result : result; + } + + private: + bool isDigit(char ch){ + return ch >= '0' && ch <= '9'; + } +};