**一. 题目描述**
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;
}
};
~~~
![](https://box.kancloud.cn/2016-01-05_568bb5ef2471b.jpg)
**四. 小结**
面试中还是经常出现这种问题的,对应的有整数转字符串。这类问题中考虑好边界条件是关键。
- 前言
- 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