LeetCode题解 第六周

来源:互联网 发布:网络搜索引擎6个字母 编辑:程序博客网 时间:2024/05/16 19:43

1. String to Integer

https://leetcode.com/problems/string-to-integer-atoi/description/


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.


Difficulty:Medium

Explanation:

本题的难点不在于如何实现从字符串转到整数,而是在于对各种情况的考虑,当把所有可能出现的字符串输入情况都考虑到了自然就能把本题做出来了。
这道题目主要就是要考虑输入字符串的情况,并对不同的情况进行不同的处理。
1.输入的字符串是规范的字符串,即这个字符串刚好可以完整的转换成一个整数。
2.输入的字符串开头如果包含空格,则忽略空格
3.输入的字符串中间包含非法字符(‘0’~‘9’)范围外的字符,则只转换这个字符前的子字符串。
4.输入的字符串是以‘+’或‘-’号开头的,转换时要考虑整数的正负。
5.输入的第一个非空字符序列如果不是合法的话,则返回零
6.注意转换后的整数是否超出了INT_MIN~INT_MAX这个范围

code:

class Solution {public:    int myAtoi(string str){        if(str=="") return 0;  // str.length()==0 等价于 str=="",故条件不必写为if(str=="" || str.length()==0)         long long final, res=0;        int len=str.length();        int sign=1;        int sign_count=0;for(int i=0; i<len; i++)        {        char ch=str[i];if(ch=='-' || ch=='+') sign_count++;if(sign_count<=1){if(ch<='9' && ch>='0'){res = res*10+ch-'0';if(res> INT_MAX && sign==1) return INT_MAX;   // 当输入数超过INT_MAX或INT_MIN时,需及时退出,如果等计算完再返回,final会变为1(存储越界)if(res< INT_MIN && sign==-1) return INT_MIN;if(i+1<len && str[i+1]==' ') break;}else if(ch=='-' || ch=='+') {if(ch=='-') sign=-1;if(i+1<len && str[i+1]==' ') break;}else if(ch==' ') ;  // 开头的空格忽略掉else break;  // 输入不合法,退出循环}  else return 0;}        if(res>= INT_MIN && res <= INT_MAX) final=res*sign;        else if(sign==1) final = INT_MAX;        else if(sign==-1) final = INT_MIN;  // 如果越出整数边界,返回相应的值 return final; // -2147483648[(signed int)0x80000000] ~ 2147483647(0x7FFFFFFF)    }   };

原创粉丝点击