**一. 題目描述**
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Requirements for atoi:
The function first discards as many whitespace characters as necessary 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. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
**二. 題目分析**
該問題的內容很長,其實主要是描述一些可能的邊界問題。對于整數來說,兩大問題就是是正負號的問題和是整數范圍是否越界的問題。
思路比較簡單,就是先去掉多余的空格字符,然后讀符號(注意正負號都有可能,也有可能沒有符號),接下來按順序讀數字,結束條件有三種情況:
1. 異常字符出現(按照atoi函數的規定是,把異常字符起的后面全部截去,保留前面的部分作為結果);
2. 數字越界(返回最接近的整數);
3. 字符串結束。
**三. 示例代碼**
只要注意邊界問題,編程沒有太大難度,由于時間有限,先借鑒了別人的程序。
~~~
#include <iostream>
using namespace std;
// 時間復雜度O(n),空間復雜度O(1)
class Solution
{
public:
int atoi(const char *str)
{
int num = 0;
int sign = 1; // 正負數標記
int strSize = strlen(str);
int index = 0;
while (str[index] == ' ' && index < strSize)
index++;
if (str[index] == '+')
++index;
else if (str[index] == '-')
{
sign = -1;
++index;
}
for (; index < strSize; ++index)
{
if (str[index] < '0' || str[index] > '9')
break;
// 以下操作檢查是否溢出
if (num > INT_MAX / 10 || ((num == INT_MAX / 10) && (str[index] - '0') > (INT_MAX % 10)))
return sign == -1 ? INT_MIN : INT_MAX;
num = num * 10 + str[index] - '0';
}
return num * sign;
}
};
~~~

**四. 小結**
面試中還是經常出現這種問題的,對應的有整數轉字符串。這類問題中考慮好邊界條件是關鍵。
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016騰訊軟件開發筆試題)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契數列問題)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波蘭式的計算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和問題)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching