I'm given a task: Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string. Here is my solution
static string FakeBinary(string number)
{
string output = "";
int integerRepresentation = int.Parse(number);
int[] digitsArray = new int[number.Length];
for (int i = digitsArray.Length; i <digitsArray.Length; i )
{
int currentDigit = integerRepresentation % 10;
integerRepresentation /= 10;
if (currentDigit > 5)
{
digitsArray[i] = 1;
}
else if (currentDigit < 5)
{
digitsArray[i] = 0;
}
output = digitsArray[i];
}
return output;
}
I have no idea what am I doing wrong, please help.
CodePudding user response:
Inital loop value is the mistake
class Program { static string FakeBinary(string number) { string output = ""; int integerRepresentation = int.Parse(number); int[] digitsArray = new int[number.Length]; for (int i = 0; i < digitsArray.Length; i ) { int currentDigit = integerRepresentation % 10; integerRepresentation /= 10; if (currentDigit > 5) { digitsArray[i] = 1; } else if (currentDigit < 5) { digitsArray[i] = 0; } output = digitsArray[i]; } return output; } public static void Main(string[] args) { FakeBinary("4567"); } }
CodePudding user response:
Here is my solution, check it out if interested
static string FakeBinary(string number)
{
string output = "";
int integerRepresentation = int.Parse(number);
int[] digitsArray = new int[number.Length];
for (int i = 0;i <digitsArray.Length; i )
{
int currentDigit = integerRepresentation % 10;
integerRepresentation /= 10;
if (currentDigit > 5)
{
digitsArray[digitsArray.Length - i -1] = 1;
}
else if (currentDigit < 5)
{
digitsArray[digitsArray.Length - i - 1] = 0;
}
output = digitsArray[i];
}
return output;
}