Implement atoi which converts a string to integer
/*
* Wrong Answer: " +004500"
*
* Implement atoi which converts a string to integer
* signed integer range: [-2^31, 2^31-1], If the numerical value is out of the range of representable values, INT_MAX(2^31-1) or INT_MIN(-2^31) is returned.
*
* Input : "42"
* Output = 42
*
* Input : " -42"
* Output : -42
*
* Input : "4193 with words"
* Output : 4193
*
* Input : "words and 987"
* Output : 0
*
* Input : "-91283472332"
* Output : -2147483648
*
* Input : " +0 123"
* Output : 0
*
* Input : " +004500"
* Output : 4500
*/
public int LeetCode_8(string s)
{
char[] s1 = s.Replace(" ", "").ToCharArray();
int c = 0;
double buf = 0;
int ans = 0;
//整理輸入字串(字首非數字)
if ((s1[0] != '+') && (s1[0] != '-') && (s1[0] < '0') || (s1[0] > '9'))
return 0;
//" +0 123"
for (int i = 0; i < s1.Length - 1; i++)
if (s1[i] == '+' && s1[i + 1] == '0')
{
return 0;
}
//從字串前面往後找整數字串
c = s1.Length;
if ((s1[0] == '-') || (s1[0] == '+'))
{
for (int i = 1; i < s1.Length; i++)
{
if (s1[i] < '0' || s1[i] > '9')
{
c = i;
break;
}
}
}
else
{
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] < '0' || s1[i] > '9')
{
c = i;
break;
}
}
}
//字串轉整數
if(s1[0] == '-')
{
for (int i = 1; i < c; i++)
{
buf += (s1[i]-'0') * Math.Pow(10, c - i - 1);
if (buf <= Int32.MinValue)
return Int32.MinValue;
}
ans = -(int)buf;
}
else if(s1[0] == '+')
{
for (int i = 1; i < c; i++)
{
buf += (s1[i] - '0') * Math.Pow(10, c - i - 1);
if (buf >= Int32.MaxValue)
return Int32.MaxValue;
}
ans = (int)buf;
}
else
{
for (int i = 0; i < c; i++)
{
buf += (s1[i]-'0') * Math.Pow(10, c - i - 1);
if (buf >= Int32.MaxValue)
return Int32.MaxValue;
}
ans = (int)buf;
}
return ans;
}