fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4.  
  5. // returns '1' for true, '0' for false.
  6. char exclusive_or(char a, char b)
  7. {
  8. return (a != b) + '0' ;
  9. }
  10.  
  11. std::string to_gray(const std::string& binary)
  12. {
  13. std::string result(1, binary[0]);
  14. result.reserve(binary.size() + 1);
  15.  
  16. for (unsigned i = 1; i < binary.size(); ++i)
  17. result += exclusive_or(binary[i - 1], binary[i]);
  18.  
  19. return result;
  20. }
  21.  
  22. int main()
  23. {
  24. std::string number;
  25.  
  26. std::cout << std::right ;
  27.  
  28. std::cout << " bin = gray\n" ;
  29. while ( std::getline(std::cin, number) && !number.empty() )
  30. {
  31. std::cout << std::setw(4) << number ;
  32. std::cout << " = " ;
  33. std::cout << std::setw(4) << to_gray(number) << '\n' ;
  34. }
  35. }
Success #stdin #stdout 0s 3432KB
stdin
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
stdout
 bin = gray
   0 =    0
   1 =    1
  10 =   11
  11 =   10
 100 =  110
 101 =  111
 110 =  101
 111 =  100
1000 = 1100
1001 = 1101
1010 = 1111
1011 = 1110
1100 = 1010
1101 = 1011
1110 = 1001
1111 = 1000