This is my function of converting binary to Gray Code.
public void convert(String bin)
{
char[] b = bin.toCharArray();
char[] g = new char[100];
System.out.print(g[0]);
for(int i=1;i<b.length;i++)
{
System.out.print(g[i] = (b[i-1] + b[i]) - 96);
if(g[i] == '2')
{
System.out.print(0);
i++;
continue;
}
System.out.print(g[i] - 0);
}
}
I have above function which works perfectly fine but I want to return the converted string from this function. So I come up with the code given below, which is not working fine and it only give me the single digit which I store in starting i.e. g[0] = b[0] as a result.
public String convert(String bin)
{
char[] b = bin.toCharArray();
char[] g = new char[100];
g[0] = b[0];
for(int i=1;i<b.length;i++)
{
g[i] = (char)((b[i-1] + b[i]) - 96);
if(g[i] == '2')
{
g[i] = 0;
i++;
continue;
}
g[i] = g[i] - 0;
}
String gray = String.valueOf(g);
return gray;
}
How can I do this so that it give me the result which I want.
Thanks
new String(g).g[i] = g[i] - 0;has no effect andg[i] = 0;is probably wrongString valueOf(char g[])translates tonew String(g)