Zurc Zurc - 11 days ago 5
C# Question

Flip the binary

I want to flip the binary to

1
or
0
. For example I have the binary
101
the output should be
010
. I've been trying to iterate through the array and change the value but the output is always
0, 000, 0000, 00
.

HERE is the code i'm working with:

static void Main(string[] args)
{
Console.Write("Input Binary: ");
String x = Console.ReadLine();
char[] bin = x.ToCharArray();
int[] nbin = new int[bin.Length];

for (int i = 0; i < bin.Length; i ++)
{

int a = bin[i];
if(a == 0)
{

nbin.SetValue(1, i);

}
if(a == 1)
{

nbin.SetValue(0, i);
}

}

foreach (var e in nbin)
{
Console.Write(e);
}

Console.Read();
}

Answer

You are comparing integers with characters, which would probably never get you the expected result because you are comparing with the character's ASCII value.

Characters are represented by '' in C#, so you should add them to the 0s and 1s in the condition:

if(a == '0')
{

    nbin.SetValue(1, i);

}
if(a == '1')
{

    nbin.SetValue(0, i);
}

You can also print an error message if the user enters something weird:

if(a == '0')
{

    nbin.SetValue(1, i);

} else if(a == '1')
{

    nbin.SetValue(0, i);
} else 
{
    Console.WriteLine("Input Invalid!");
    return;
}
Comments