LeetCode/8. String to Integer (atoi).md
2018-12-07 16:39:00 +08:00

40 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [8. String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/)
# 思路
实现atoi函数即将字符串转换为对应数字。
> `atoi()`函数用来将字符串转换成整数(int),其原型为:
`int atoi (const char * str);`
atoi函数会扫描参数 str 字符串跳过前面的空白字符例如空格tab缩进等
直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。
按照上面的说明转换即可题目说了空白字符只考虑空格为了防止溢出将结果用long long型存放。
# C++
``` C++
class Solution {
private:
int char2digit(const char c){ // 将字符转换为对应数字,若非数字则返回-1
if(c >= '0' && c <= '9') return int(c - '0');
return -1;
}
public:
int myAtoi(string str) {
long long res = 0;
int len = str.size(), i = 0, minus_sign = 0;
while(i < len && str[i] == ' ') i++;
if(i < len && (str[i] == '-' || str[i] == '+'))
if(str[i++] == '-') minus_sign = 1;
while(i < len){
int digit = char2digit(str[i]);
if(digit == -1) break;
res = res * 10 + digit;
if(minus_sign == 1 && -res < INT_MIN) return INT_MIN;
else if(minus_sign == 0 && res > INT_MAX) return INT_MAX;
i++;
}
return minus_sign == 1 ? -res: res;
}
};
```