Binary to Greycode

 

Binary to Greycode



Problem Description


In mathematics and digital electronics, a binary number is a number expressed in the base-2 numeral system or binary numeral system, which uses only two symbols: typically 0 (zero) and 1 (one).The base-2 numeral system is a positional notation with a radix of 2. Each digit is referred to as a bit. Because of its straightforward implementation in digital electronic circuitry using logic gates, the binary system is used by almost all modern computers and computer-based devices.

The modern binary number system was studied in Europe in the 16th and 17th centuries by Thomas Harriot, Juan Caramuel y Lobkowitz, and Gottfried Leibniz. However, systems related to binary numbers have appeared earlier in multiple cultures including ancient Egypt, China, and India. Leibniz was specifically inspired by the Chinese


The reflected binary code (RBC), also known just as reflected binary (RB) or Gray code after Frank Gray, is an ordering of the binary numeral system such that two successive values differ in only one bit (binary digit). The reflected binary code was originally designed to prevent spurious output from electromechanical switches. Today, Gray codes are widely used to facilitate error correction in digital communications such as digital terrestrial television and some cable TV systems.


Write a program to convert the given binary code to gray code

Logic Test Case 1


Input (stdin)

100


Expected Output


110

Logic Test Case 2


Input (stdin)

110


Expected Output


101





CODE AREA


import static java.lang.StrictMath.pow;

import java.util.Scanner;

public class TestClass

{

    public static void main(String[] args) 

    {

        int a, b, x, result = 0, i = 0;

        Scanner s = new Scanner(System.in);

        

        x = s.nextInt();

        while(x != 0)

        {

            a = x % 10;

            x = x / 10;

            b = x % 10;

            if((a & ~ b) == 1 || (~ a & b) == 1)

            {

                result = (int) (result + pow(10,i));

            }

            i++;

        }

        System.out.println(""+result);

    }

}

Post a Comment

0 Comments