Leetcode
  • Leetcode Questions
  • Runtime Screenshots
  • DataStructure
    • Leetcode 394. Decode String
    • Leetcode 225. Implement Stack Using Queues
    • Leetcode 336. Palindrome Pairs
    • Leetcode 316. Remove Duplicate Letters
    • Leetcode 206. Reverse Linked List
    • Leetcode 347. Top K Frequent Elements
    • Leetcode 227. Basic Calculator II
    • Leetcode 224. Basic Calculator
  • Linear
    • Leetcode 23. Merge k Sorted Lists
    • Leetcode 48. Rotate Image
    • Leetcode 6. ZigZag Conversion
    • Leetcode 438. Find All Anagrams in a String
    • Leetcode 189. Rotate Array
    • LeetCode 56. Merge Intervals
    • Leetcode 4. Median of Two Sorted Array
    • Leetcode 3. Longest Substring Without Repeating Characters
    • Leetcode 8. String to Integer (atoi)
    • Leetcode 5. Longest Palindromic Substring
    • Leetcode 11. Container With Most Water
  • Tree
    • Leetcode 103. Binary Tree Zigzag Level Order Traversal
    • Leetcode 508. Most Frequent Subtree Sum
    • Leetcode 226. Invert Binary Tree
    • Leetcode 222. Count Complete Tree Nodes
    • Leetcode 250. Count Univalue Subtrees
    • Leetcode 285. Inorder Successor in BST
    • Leetcode 230. Kth Smallest Element in a BST
    • Leetcode 543. Diameter of Binary Tree
    • Leetcode 199. Binary Tree Right Side View
  • Math
    • Leetcode 50. Power(x, n)
    • Leetcode 166. Fraction to Recurring Decimal
    • Leetcode 7. Reverse Integer
    • Leetcode 360. Sort Transformed Array
    • Leetcode 367. Valid Perfect Square
    • Leetcode 12. Integer to Roman
  • DynamicProgramming
    • Leetcode 10. Regular Expression Matching
    • Leetcode 253. Meeting Rooms II
    • Leetcode 303. Range Sum Query
    • Leetcode 22. Generate Parentheses
  • Graph
    • Leetcode 142. Linked List Cycle II
    • Leetcode 261. Graph Valid Tree
    • Leetcode 339. Nested List Weight Sum
    • Leetcode 207. Course Schedule
  • OODesign
    • Leetcode 295. Find Media From Data Stream
Powered by GitBook
On this page
  • 题目
  • Thoughts
  • Solution
  • Complexity Analysis
  • Extension
  • Summary
  • Reference

Was this helpful?

  1. Linear

Leetcode 8. String to Integer (atoi)

题目

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as neccesssary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ' ' is considered as whitespace character.

  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^32 - 1]. If the numerical value is out of the range of repressentable values, INT_MAX (2^31 - 1) or INT_MIN (-2^31) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

Thoughts

The most challenging part of this question is to handle all tricky edge cases. Personally I would approach this problem with the following three steps: 1. Skip all whitespace in the beginning (also handle the whitespace only case). 2. Check sign if the first non whitespace character is a sign. 3. Keep constructing result until first non-digit is met (also handle the overflow case).

Solution

The following solution strictly follows above three steps for better readability. Yet, it uses two while loops which are unneccessary. Although personally I prefer the current solution that are easier to follow through (and debug), we can opt to use one single loop and check all possible cases within it. By this means, the algorithm is generally faster, despite they have the same time complexity.

class Solution {
    public int myAtoi(String str) {

        int i = 0;
        int sign = 1;
        long res = 0;

        // skip white space
        while (i < str.length() && str.charAt(i) == ' ') {
            i++;
        }

        // all white space
        if (i == str.length()) return 0;

        // check sign
        char first = str.charAt(i);
        if (first == '+' || first == '-') {
            i++;
            if (first == '-') sign = -1;
        }

        // construct the result while digits
        while (i < str.length() && Character.isDigit(str.charAt(i))) {
            res = res * 10 + Character.getNumericValue(str.charAt(i));
            i++;
            // check boundary
            if (res * sign > Integer.MAX_VALUE) return Integer.MAX_VALUE * sign;
            if (res * sign < Integer.MIN_VALUE) return Integer.MIN_VALUE * sign;
        }

        return (int) res * sign;
    }
}

Complexity Analysis

  • Time Complexity: O(n). We have to iterate through all characters in the string.

  • Space Complexity: O(1). We don't use any extra space.

Extension

If we are asked to convert string's all digital characters to integer (instead of the first sequence of digital chars), are you able to do it?

Summary

Edge cases are important. We have to think thoroughly to cover all cases in a timely manner and then find solutions that handle them with minimum conditional checks. An elegant solution is the one that cover many complicated cases with concise codes.

I realize on Leetcode, the questions that require deliberate consideration on edge cases recieve most downvotes. However, we do need to practice dealing with complex edge cases.

Reference

PreviousLeetcode 3. Longest Substring Without Repeating CharactersNextLeetcode 5. Longest Palindromic Substring

Last updated 5 years ago

Was this helpful?

original series

Mao's