转换字符串为浮点数
namespace ConsoleApplication1
{
class TestFaiureException : Exception
{
public TestFaiureException(string s)
: base(s)
{
}
}
class MyUtils
{
public static void _Main(string[] args)
{
string[] testData = new string[] { "123", "-123", "123.1", "-123.1", "0", "0.1", "1.2.3", "-.3", "0.a", ".1" };
double[] expected = new double[] { 123, -123, 123.1, -123.1, 0, 0.1, 0, 0, 0, 0 };
try
{
delegateConvertToFloat dctf = ConvertToFloat;
for (int i = 0; i < testData.Length; i++)
{
TestConvertToFloat(dctf, testData[i], expected[i]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
delegate double delegateConvertToFloat(string s);
private static void TestConvertToFloat(delegateConvertToFloat func, string input, double expected)
{
try
{
double actual = func(input);
if (expected == actual)
{
return;
}
else
{
throw new TestFaiureException(string.Format("expected: {0}, actual: {1}", expected.ToString(), actual));
}
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
}
catch (TestFaiureException ex)
{
Console.WriteLine(ex.Message);
}
}
private static double ConvertToFloat(string s)
{
if (string.IsNullOrEmpty(s))
{
throw new ArgumentNullException("s");
}
string pattern = @"^[+-]?\d+(\.\d+)?$";
if (!Regex.IsMatch(s, pattern, RegexOptions.Singleline))
{
throw new FormatException("not legal digit: " + s);
}
string digits;
bool isNagative = false;
if (s.StartsWith("+"))
{
digits = s.Substring(1);
}
else if (s.StartsWith("-"))
{
digits = s.Substring(1);
isNagative = true;
}
else
{
digits = s;
}
int dot = digits.IndexOf(".");
int ldot;
int rdot;
if (dot == -1)
{
dot = digits.Length;
ldot = digits.Length - 1;
rdot = digits.Length;
}
else
{
ldot = dot - 1;
rdot = dot + 1;
}
int len = digits.Length;
double lResult = 0;
double rResult = 0;
while (ldot >= 0 || rdot < len)
{
if (ldot >= 0)
{
lResult = lResult + (digits[ldot] - '0') * Math.Pow(10, (dot - 1) - ldot);
ldot--;
}
if (rdot < len)
{
rResult = rResult + (digits[rdot] - '0') * Math.Pow(10, dot - rdot);
rdot++;
}
}
return isNagative ? (-1) * (lResult + rResult) : (lResult + rResult);
}
}
}
这才是真正的O(N)
class StringToFloat
{
private static bool InternalValidate(string strFloat)
{
return true;
}
public static double ConvertTodouble(string s)
{
if (!InternalValidate(s))
{
throw new FormatException(s);
}
double sum1 = 0;
double sum2 = 0;
bool meetDot = false;
int dotIndex = 1;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '.')
{
meetDot = true;
continue;
}
if (!meetDot)
{
sum1 = sum1 * 10 + (s[i] - '0');
continue;
}
if (meetDot)
{
sum2 = sum2 + (s[i] - '0') * Math.Pow(0.1, dotIndex);
dotIndex++;
continue;
}
}
return sum1 + sum2;
}
}