码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - 8. String to Integer (atoi)

时间:2016-01-12 10:04:52      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

题目:  

  Implement atoi to convert a string to an integer.

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. 忽略字符串前面所有的空白格。

  2. 从第一个字符开始转换数字,判断正负号,遇到非1~9字符则停止转换并返回已得到的值。

  3. 防止溢出(-2147483648~2147483647),溢出则返回相应门限值。

  4. 若不能合理转换,返回0。

解题关键:

  提取题目要去根据条件过滤非法字符,实行转换。

  自己进行测试的时候要设计多个测试用例,包括测试正负门限值、空字符串、带不同特殊符号的字符串等(个人感觉考察测试用例设计能力)。

C#代码:

技术分享
public class Solution {
    public int MyAtoi(string str)
    {
        if (string.IsNullOrEmpty(str)) return 0;
        char[] charArr = str.ToCharArray();
        //1. judge the string is positive or negative or illegal
        int sign = 0;
        int result = 0;
        int i = 0;
        while (i<str.Length && charArr[i] ==  ) i++;
        if (charArr[i] == -)
            sign = -1;
        else if (charArr[i] == +)
            sign = 1;     
        //2. calculate the result   
        while(charArr[i]>=0 && charArr[i]<=9)
        {            
            int num = int.Parse(charArr[i].ToString());
            //in case of overflow
            if ((int.MaxValue - num) / 10 < result || ((int.MaxValue - num)/10==result&&charArr[i]-0>7)) 
            {
                if (sign > 0)
                    return int.MaxValue;
                else
                    return int.MinValue;
            }
            result = result * 10 + num;
        }
        return sign * result;
    }
}
View Code

 

LeetCode - 8. String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/xquancnblogs/p/5123362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!