实现atoi这个函数, public int atoi(String str),传入字符串str可以返回整数,请仔细考虑一下字符串的各种情况!
String to Integer: Case分析
- 正常数字
Sample:”123”,”0”,”1” ,"-1"
- 普通特殊字符:
Sample: "000","001","-001"
- 正负号问题
- 含有正负号
Sample: " -123", " +123", "-123", "+123","--123","++123"," -004500"
- 空格问题
- 含有空格
Sample: " 123","123 123","123 "
- 包含特殊符号
- 字母,其它特殊符号
Sample: "*123","*abc","~123","123~", "a123","12a3", "12+3","12-3"
- 空的字符串
Sample: string.Empty,null,""," "
- 边界问题
- 正常或者超过Int32最大和最小值,输出最大 或最小Int32
Sample: "-2147483648","2147483647"
Sample: "-214748364800","214748364700"
Snapshot:
Source Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//http://www.cnblogs.com/binyao/p/5026406.html namespace StringtoInteger
{
class Program
{
static void Main(string[] args)
{
string[] str = { string.Empty,null,""," ",
"","","","","","-1","-001",
"","123 123","123 ",
" -123", " +123",
"-123", "+123","--123","++123"," -004500",
"*123","*abc","~123","123~",
"a123","12a3",
"12+3","12-3",
"-2147483648","",
"-214748364800","" };
StringtoInteger(str);
} public static void StringtoInteger(string[] str)
{
Console.WriteLine("StringtoInteger Result is:");
foreach (string s in str)
{
Console.Write("Test Data:{0}", s);
Console.WriteLine(" Result:{0}", StringtoInteger(s));
}
} public static int StringtoInteger(string str)
{
int sign = ;
int i = ;
int result = ; if (string.IsNullOrEmpty(str))
{
return result;
} while (i < str.Length && ((str[i] >= '' && str[i] <= '') || str[i] == ' ' || str[i] == '-' || str[i] == '+'))
{
if (str[i] == ' ' && (result == && sign == ))
{
i++;
}
else if (str[i] == '+' && (result == && sign == ))
{
sign = ;
i++;
}
else if (str[i] == '-' && (result == && sign == ))
{
sign = -;
i++;
}
else if (str[i] >= '' && str[i] <= '')
{
if (result > (int.MaxValue - (str[i] - '')) / )
{
if (sign == || sign == )
return int.MaxValue;
return int.MinValue;
} result = result * + str[i] - '';
i++;
}
else
{
if (sign == )
return result;
return result * sign;
}
} if (sign == )
return result;
return result * sign;
}
}
}