1. Introduction
This is a face-to-face question. At that time, I used strings to separate the question. The specific requirements are as follows:
Convert a non-negative integer to int []. For example, if 1234 is input, int [4] {1, 2, 3, 4} is obtained }.
This evening I was interested in using the TDD method to make a version without converting strings. The main feature is to lose the decimal point value when the floating point is converted into an integer.
* Note: unit testing and implementation code are alternating during code writing, not as clearly separated as shown below.
2. unit test: [TestFixture]
Public class IntToArrayHelperTests: IntToArrayHelper
{
[Test]
Public void TestGetNumberAt ()
{
Assert. AreEqual (0, GetNumberAt (0, 1 ));
Assert. AreEqual (1, GetNumberAt (1, 1 ));
Assert. areequal (1, getnumberat (21, 1 ));
Assert. areequal (1, getnumberat (10001, 1 ));
Assert. areequal (2, getnumberat (21, 2 ));
Assert. areequal (1, getnumberat (87654321, 1 ));
Assert. areequal (2, getnumberat (87654321, 2 ));
Assert. areequal (7, getnumberat (87654321, 7 ));
Assert. areequal (8, getnumberat (87654321, 8 ));
}
[Test]
Public void TestGetDigitCount ()
{
Assert. AreEqual (1, GetDigitCount (0 ));
Assert. AreEqual (1, GetDigitCount (1 ));
Assert. AreEqual (1, GetDigitCount (9 ));
Assert. AreEqual (2, GetDigitCount (10 ));
Assert. AreEqual (10, GetDigitCount (Int32.MaxValue ));
}
[Test]
Public void TestConvert ()
{
Int [] a = new int [1] {0 };
Assert. AreEqual (a, Convert (0 ));
Int [] B = new int [1] {1 };
Assert. AreEqual (B, Convert (1 ));
Int [] c = new int [10] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
Assert. AreEqual (c, Convert (1234567890 ));
Int [] d = new int [9] {9, 8, 7, 6, 5, 4, 3, 2, 1 };
Assert. AreEqual (d, Convert (987654321 ));
Int [] max = new int [10] {2, 1, 4, 7, 4, 8, 3, 6, 4, 7 };
Assert. AreEqual (max, Convert (Int32.MaxValue ));
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException)]
Public void TestConvertWithNegative ()
{
Convert (-1 );
}
}
3. Implementation Code: Public class IntToArrayHelper
{
Protected int GetNumberAt (int value, int digit)
{
Int contrastNumber = (int) Math. Pow (10, digit );
Int digitCutter = (int) Math. Pow (10, digit-1 );
Return (value-value/contrastNumber * contrastNumber)/digitCutter;
}
Protected int GetDigitCount (int value)
{
If (value = 0)
Return 1;
Return (int) Math. Log10 (value) + 1;
}
Public int [] Convert (int value)
{
If (value <0)
Throw new argumentoutofrangeexception ("value", "not less than zero .");
Int digitcount = getdigitcount (value );
Int [] result = new int [digitcount];
For (INT I = 0; I <digitcount; ++ I)
{
Int Index = digitcount-I-1;
Result [index] = GetNumberAt (value, I + 1 );
}
Return result;
}
}