Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package miscellaneous;
- import java.util.Scanner;
- public class GrayCodeMain
- {
- public static void main(String... args)
- {
- String a = "", b = "";
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter the first 8-bit number: ");
- a = scan.next();
- System.out.print("\nEnter the second 8-bit number: ");
- if(scan.hasNext())
- b = scan.next();
- System.out.print("\nIs one the Gray code of the other?: ");
- if(GrayCode.checkGray(a, b))
- System.out.print("Yes.");
- else
- System.out.print("No.");
- }
- }
- class GrayCode
- {
- static boolean checkGray(String a, String b)
- {
- long first = Long.parseLong(a, 2);
- long second = Long.parseLong(b, 2);
- long encode_1 = encode(first);
- long encode_2 = encode(second);
- long decode_1 = decode(first);
- long decode_2 = decode(second);
- if((encode_1 == second) || (encode_2 == first))
- return true;
- if((decode_1 == second) || (decode_2 == first))
- return true;
- return false;
- }
- static long encode(long n)
- {
- long p = n ^ (n >>> 1);
- return p;
- }
- static long decode(long n)
- {
- long p = n;
- while((n >>> 1) != 0)
- p ^= n;
- return p;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement