One major improvement would be to just use what is supplied through .NET:
Convert.ToString(int, 2);
where int
is your supplied argument.
Convert.ToString Method (Int32, Int32)
Converts the value of a 32-bit signed integer to its equivalent string representation in a specified base.
Note that this returns you a string value like 10000110100001
, which is the representation of a binary number. In your code you store them as string representations and in separate entries in your collection, which is not the way a number should be stored. It's like creating an array with values "1" and "2" to represent the number 12.
If this is your intention then you can always work towards that of course but it might be an indication that something else is wrong for needing it like that.
However if you want to stay with your own implementation, there are a few things you could change around:
public List<string> Conversion2(int x) { var bitConversion = new List<string>(); while (x >= 0) { if (x == 0) { bitConversion.Add("0"); break; } bitConversion.Add((x % 2).ToString(CultureInfo.InvariantCulture)); x /= 2; } bitConversion.Reverse(); return bitConversion; }
- Remove the unnecessary
result
variable - Contract
x = x / 2
to x /= 2
(compound assignment operator)