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 ie 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
public static String convert(String bin)
{
//System.out.println( "The Gray Equivalent Is: ");
char[] b = bin.toCharArray();
StringBuilder g = new StringBuilder(); // Use StringBuilder
g.append(b[0]);
//System.out.print(g[0]);
for(int i=1;i<b.length;i++)
{
int val = (int)b[i-1] ^(int) b[i]; // use exclusive-or( ^ )
if(val == '2')
{
//System.out.print(0);
g.append(0);
i++;
continue;
}
//System.out.print(g[i] - 0);
g.append(val);
}
String gray = String.valueOf(g);
return gray;
}
I see what you want to achieve. But you are mistaking the integer values with the character values. Look:
An int
is a integer numeric value, which can contain positive and negative numbers: -3, -2, -1, 0, 1, 2, 3...
A char
is still a numeric value, but represented as letters: 'a'(97), 'b'(98), 'c'(99)...
I know you already know this, because you have been careful enough to compute the sum of two chars and normalize it substracting 2*'0' (=96). Good.
But you must notice that every number included in your code is implicitly an int
. Now, realise that you are mixing ints
and chars
in several lines:
if(g[i] == '2')
g[i] = 0;
g[i] = g[i] - 0;
My suggestion: Follow an order:
int digit0=b[i - 1]-'0'; int digit1=b[i]-'0';
int digit0=b[i - 1]-'0'; int digit1=b[i]-'0';
int result=digit0 + digit1; if (result==2) { result=0; }
int result=digit0 + digit1; if (result==2) { result=0; }
g[i]=(char)(result + '0');
In the last place, you must also control the length of the arrays: If you know what is the length of the input array, you should pre-size the output array with the same length.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.