Friday, 14 July 2017

UVa 11173 - Grey Codes Using Bitset

This question asks to convert a decimal to gray code and print the decimal value of this gray code.


Code


Language: C++ using Bitset

#include <iostream>
using namespace std;
#include <bits/stdc++.h>

int
main()
{

  int t;
  cin >> t;
  while (t--) {
    int temp, garbage;
    cin >> garbage >> temp;
    if (temp == 0) {
      cout << "0\n";
      continue;
    }
    bitset<32> aux(temp);
    bitset<32> b(0);
    int l = int(log2(temp)) + 1;
    b.set(l - 1);
    for (int i = l - 2; i >= 0; i--) {
      if (aux.test(i + 1) ^ aux.test(i)) {
        b.set(i);
      }
    }
    cout << b.to_ulong() << endl;
  }

  return 0;
}

No comments:

Post a Comment