cses

My solution for the coding challenges of cses.fi
git clone https://git.tronto.net/cses
Download | Log | Files | Refs | README

gray_code_2205.cpp (435B)


      1 #include <iostream>
      2 #include <format>
      3 
      4 void print(int number, int ndigits) {
      5 	std::cout << std::format("{0:0{1}b}", number, ndigits) << "\n";
      6 }
      7 
      8 void print_all(int& start, int digit, int ndigits) {
      9 	if (digit == 0) {
     10 		print(start, ndigits);
     11 	} else {
     12 		print_all(start, digit-1, ndigits);
     13 		start ^= 1 << (digit-1);
     14 		print_all(start, digit-1, ndigits);
     15 	}
     16 }
     17 
     18 int main() {
     19 	int n, start{0};
     20 	std::cin >> n;
     21 	print_all(start, n, n);
     22 }