Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

LeetCode Solutions

8. string to integer atoi

Time: O(n)

Space: O(1)

			

    class Solution {
        public:
         int myAtoi(string s) {
           trim(s);
           if (s.empty())
             return 0;
       
           const int sign = s[0] == '-' ? -1 : 1;
           if (s[0] == '+' || s[0] == '-')
             s = s.substr(1);
       
           long num = 0;
       
           for (const char c : s) {
             if (!isdigit(c))
               break;
             num = num * 10 + (c - '0');
             if (sign * num < INT_MIN)
               return INT_MIN;
             if (sign * num > INT_MAX)
               return INT_MAX;
           }
       
           return sign * num;
         }
       
        private:
         void trim(string& s) {
           s.erase(0, s.find_first_not_of(' '));
           s.erase(s.find_last_not_of(' ') + 1);
         }
       };				 


    class Solution {
        public int myAtoi(String s) {
          s = s.strip();
          if (s.isEmpty())
            return 0;
      
          final int sign = s.charAt(0) == '-' ? -1 : 1;
          if (s.charAt(0) == '+' || s.charAt(0) == '-')
            s = s.substring(1);
      
          long num = 0;
      
          for (final char c : s.toCharArray()) {
            if (!Character.isDigit(c))
              break;
            num = num * 10 + (c - '0');
            if (sign * num <= Integer.MIN_VALUE)
              return Integer.MIN_VALUE;
            if (sign * num >= Integer.MAX_VALUE)
              return Integer.MAX_VALUE;
          }
      
          return sign * (int) num;
        }
      }	  


    class Solution:
    def myAtoi(self, s: str) -> int:
      s = s.strip()
      if not s:
        return 0
  
      sign = -1 if s[0] == '-' else 1
      if s[0] in {'-', '+'}:
        s = s[1:]
  
      num = 0
  
      for c in s:
        if not c.isdigit():
          break
        num = num * 10 + ord(c) - ord('0')
        if sign * num <= -2**31:
          return -2**31
        if sign * num >= 2**31 - 1:
          return 2**31 - 1
  
      return sign * num  


Click on sidebar top menu and then click on any leetcode question to see its solution code in c++ ,java and python.


learn more about leetcode study guide =>

Leetcode study plan for FAANG

Topic wise problems for Beginners DS - Algorithms with LEETCODE

List of Algorithms and data structures for Competitive Programming