'string of digits and how to transform it to string of 0 and 1 depending on condition
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.
Solution 1:[1]
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"); } }
Solution 2:[2]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ramji |
| Solution 2 | Mark |
