Combined mathematical exercises (Gray code generation)

Source: Internet
Author: User
Exercise 2: generate a gray code /************************************ * *********** // obtain the next code (the parameter code is the current Gray Code) for each function call) void gray (int n, int * Code) {int T = 0; For (INT I = 0; I <n; I ++) T + = Code [I]; if (T % 2 = 1) For (n --; Code [N]! = 0; n --); Code [n-1] = 1-code [n-1];} generate the Gray code based on the algorithm provided in the book and use the above function. However, I used the following method to generate the Gray Code ***************************** * *******************/# include <iostream> # include <fstream> using namespace STD; fstream fout ("out.txt", IOS: Out); // starts from 000... 000 starts to 100... the gray code ending with 000 is 0, 1, 2... N // decimaltogray (x) returns the X Gray code (in decimal format) int decimaltogray (int x) {return x ^ (x> 1 );} // The parameter X is in the decimal format of the gray code. // call the function to return the number int graytodecimal (int x) {int y = x; while (x> = 1) y ^ = x; return y;} // output void printgray (int n, int X) {for (INT I = n-1; I >= 0; I --) fout <(x> I) & 1); fout <Endl ;}int main () {int N; while (CIN> N) {for (INT I = 0; I <(2 <(n-1); I ++) printgray (n, decimaltogray (I )); fout <Endl;} return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.