Realization __c++ of Gray code in C + +

Source: Internet
Author: User

Online to see an interview problem, is gray code conversion, before the face of the hardware encountered this problem, was the hardware to achieve. Now want to use software programming, look at the code on the Internet others, found too complex, in fact, with the gray code and binary conversion formula to achieve the simplest.

1. Natural binary code converted into binary gray code

G Highest bit = b highest bit

G I-bit = b I-i+1 or B-bit

2, binary gray code conversion into natural binary code

b Highest bit = g highest bit

b i-1 bit = g I-bit or B-I



C + + program to achieve natural binary code to binary Gray code:

vector<int> Graycode (int n) {
	vector<int> gray;
	Gray.push_back (0);
	for (int i=1; I<pow (2,n); i++)
	<span style= "White-space:pre" >	</span>gray.push_back (i^ i> >1));
	return gray;
}


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.